简体   繁体   中英

How to pass props using element in react-router v6?

I'm trying to reuse my MainSection component for two different purposes (single story and all stories). To effect this, I want to pass in a property, home, in the Routes that go to those renderings of that component. Home is true or false, and I want to render the MainSection component based on that boolean. However, I home keeps being undefined when MainSection gets rendered. The link and route are updating the URL, but not rendering with the props I want. Am I doing something wrong?

Here are my routes:

function Routes(){
  return(
    <Switch>
      <Route path="/"  element={<MainSection home={true} />} />
      <Route path="/story" element={ <MainSection home={false} />} />
    </Switch>
  )
}

and here is the code for my MainSection component:

function MainSection({ home }){
  console.log(home)
  return(
    <div className="main-section">
      <BigPicture home={ home }/>
      <Quotes home={ home }/>
    </div>
  )
}

The console log keeps returning undefined.

Thanks!

Since in the question title you state you are using react-router-dom version 6 I'll answer against that. V6 doesn't export a Switch component, it was replaced by a Routes component. Swap the Switch for the Routes component and rename your Routes component to something else to avoid the name collision.

function MainRoutes(){
  return(
    <Routes>
      <Route path="/" element={<MainSection home />} />
      <Route path="/story" element={<MainSection />} />
    </Routes>
  )
}

From here the home prop should either be treated as truthy/falsey. You can double-bang it to coerce it to a strict boolean value. Passing home through to children components should also work without issue.

function MainSection({ home }) {
  React.useEffect(() => {
    console.log(!!home);
  }, [home]);

  return(
    <div className="main-section">
      <BigPicture home={home} />
      <Quotes home={home} />
    </div>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM