'How can I return a array with React Components?

If you want to see this project running you can see the codesandbox in here.

I have a Landing component calling a ReturnPokemon component passing a string as props.

The ReturnPokemon component receives two arrays and sends back the array accordingly with the props it's receiving.

Now the Landing component has a console.log for the information that it is receiving from ReturnPokemon.

The problem with the code is Landing is not receiving the same array that ReturnPokemon receives, why is that? I need that ReturnPokemon send to Landing the same array it is receiving. How can I fix the code?

Landing:

export const Landing = () => {
  return (
    <>
      <h1>Landing</h1>
      {console.log(<ReturnPokemon pokemon="ditto" />)}
    </>
  );
};

ReturnPokemon:

import { useDitto } from "../../context/ditto";
import { useCharizard } from "../../context/charizard";
import { useState } from "react";

export const ReturnPokemon = ({ pokemon }) => {
  const [chosenPokemon, setChosenPokemon] = useState();
  const { ditto } = useDitto();
  const { charizard } = useCharizard();

  if (pokemon === "ditto") {
    setChosenPokemon(ditto);
    return { chosenPokemon };
  } else if (pokemon === "charizard") {
    setChosenPokemon(charizard);
    return { chosenPokemon };
  } else {
    return;
  }
};



Solution 1:[1]

There is no need to use useState if you are going to return it anyway. You cannot return an object in a component. You have to return some JSX element like and you can have your object inside.

Assumptions made here:

  • ditto, charizard are strings. if not just do JSON.stringify(ditto) to cast object as string

Landing:

export const Landing = () => {
  return (
    <>
      <h1>Landing</h1>
      <ReturnPokemon pokemon="ditto" />
    </>
  );
};

ReturnPokemon:

import { useDitto } from "../../context/ditto";
import { useCharizard } from "../../context/charizard";

export const ReturnPokemon = ({ pokemon }) => {
  const { ditto } = useDitto();
  const { charizard } = useCharizard();

  if (pokemon === "ditto") {
    return <div>{ditto}</div>;
  }

  if (pokemon === "charizard") {
    return <div>{charizard}</div>;
  }

  return <div></div>;
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Surya K