How to Pass State Down Nested Routes

Please see the code below for my MainComponent and the Routes in my App.js file


const [countryData, setCountryData] = React.useState([]); 
  const [searchQuery, setSearchQuery] = React.useState(''); 
  const [isLoading, setISLoading] = React.useState(true)

  const getDataAllCountries = async() => { 
    let response = await fetch("");
    let result = await response.json();

  React.useEffect(() => { 
  }, [])

App.js File with a nested route using the useParams Hook

const App = () => {
  const [isDarkMode, setIsDarkMode] = React.useState(true)
  function toggleMode () {
    setIsDarkMode(currentMode => !currentMode);
  return (
    <div >
        <Route path = "/" element = {<Header mode = {isDarkMode}  handleClick = {toggleMode}/>}>
          <Route index element = {<MainComponent mode = {isDarkMode}/>} />
          <Route path = ":name" element = {<CountryDetails mode = {isDarkMode}/>} />

The API call in the MainComponent is to get a list of all countries and data pertaining to each country and my intention is to build the project in such a way that the when a user clicks on each country, the user sees a details page. Therefore, the component (it uses the useParams Hook) will be populated based on tha value of :name in the path.

The question here is that how do I pass the countryData in the maincomponent above to the CountryDetails via props component? My intention is do execute array.find on the countryData in the Details Component so that I can get the country that was clicked and then populate the details page based on the clicked country

const clickedCountry = countryData.find(country => .....)

Have you tried this?

You could make CountryDetails receive a prop, country and while rendering the list of countries in the MainComponent, you pass the country as props. Something like this: => (
  <CountryDetails country={country} />

You might also need to show the code for CountryDetails and what you rendered in MainComponent.

If I understand correctly, you need to store the state in the App component rather than the MainComponent and also the getDataAllCountries function. And then pass getDataAllCountries as props to the MainComponent and call it there as you do now. Then you could pass countryData as props to the sibling component.


I will try this and let you know if it works.

1 Like

Thanks for your response.

I will try this and revert

1 Like

So, your idea workd fine. thanks a lot

1 Like