Home > Software design >  How can I export a state from a parent file to a child file in React js?
How can I export a state from a parent file to a child file in React js?

Time:03-18

I have a parent file in React in which I do multiple api fetch with the useState hook.
Here's the code :

const [species, setSpecies] = useState([]);

useEffect(() => {
    axios
    .get(`https://pokeapi.co/api/v2/pokemon-species/${name}`)
    .then((results) => {
        return results.data;
    })
    .then((results) => {
        setSpecies(results);
    });
}, [name]);

And here's a snippet of my code in a child element :

<li className='pokemon_data_container_list_desc'>
    {species?.flavor_text_entries?.map((sf) => 
        sf?.language?.name === 'en' && sf?.version?.name === game && 
            <>
                {sf?.flavor_text?.replace('\u000c', ' ')}
            </>
    )}
</li>

I'd like to know how I could export the 'species' from the parent to the child.

Edit : thx for the answer (sorry for the dumb question). It's my first time using React and I've never used props before (I'm trying to turn huge components into multiple little components).

CodePudding user response:

You can just pass the value as a prop to the child. This is definitely one of the basic parts of getting started with React, so I would highly recommend reading the documentation on components and props.

Here is what it may look like in your example:

function Parent() {
  const [species, setSpecies] = useState([]);

  useEffect(() => {
    axios
      .get(`https://pokeapi.co/api/v2/pokemon-species/${name}`)
      .then((results) => {
        return results.data;
      })
      .then((results) => {
        setSpecies(results);
      });
  }, [name]);

  return (
    <>
      // ...
      <Child species={species} />
    </>
  );
}

function Child({ species }) {
  return (
    <>
      // ...
      <li className='pokemon_data_container_list_desc'>
        {species?.flavor_text_entries?.map((sf) => 
          sf?.language?.name === 'en' && sf?.version?.name === game && 
            <>
              {sf?.flavor_text?.replace('\u000c', ' ')}
            </>
        )}
      </li>
    </>
  );
}

CodePudding user response:

Its an easy answer, we use props.

In the child component you can accept props like so:

function childComponent(props) {
  props.props.species // species will be sent over like an object
}

to pass the props to the childComponent

<childComponent props={species} />

CodePudding user response:

You need to pass species to the child component as a prop. Here is an example of how to do this. https://codesandbox.io/s/falling-surf-2sxdln?file=/src/App.js:0-434

// App.js
import React, { useEffect, useState } from "react";
import axios from "axios";
import SpeciesList from "./SpeciesList";

export default function App() {
  const [species, setSpecies] = useState([]);

  useEffect(() => {
    axios
      .get(`https://pokeapi.co/api/v2/pokemon-species/${name}`)
      .then((results) => setSpecies(results.data.results));
  }, []);

  return <SpeciesList species={species} />;
}

// SpeciesList.js
import React from "react";

export default function SpeciesList({ species = [] }) {
  return (
    <ul>
      {species.map((s) => (
        <li key={s.name}>{s.name}</li>
      ))}
    </ul>
  );
}
  • Related