简体   繁体   中英

Rendering components inside Route React

I want to make to render children in father component, that's how i tried to make it but browser shows nothing eventually:

const MainLayout = props => {
    return (
        <div className='main-layout'>
            <Header />
            <div className='main'>
                {props.children}
            </div>
        </div>
    )
}

App.js

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Routes>
          <Route exact path="/" render={() => (
            <MainLayout>
              <Homepage />
            </MainLayout>
          )} />
        </Routes>
      </BrowserRouter>

You should use element proprety to render your component, assuming that you are using React Router Dom V6, component propriety for anterior versions, or simply like this, by wrapping inside the Route :

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Routes>
          <Route exact path="/">
            <MainLayout>
              <Homepage />
            </MainLayout>
          </Route>
        </Routes>
      </BrowserRouter>
    </div>
   )

Hope it helps...

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Routes>
          <Route exact path="/" element={<MainLayout />}>
            <Route path="/home" element={<Homepage />} />
          </Route>
        </Routes>
      </BrowserRouter>
    </div>
  )
}

and Add a Outlet component inside MainLayout Component

const MainLayout = props => {
  return (
    <>
      <div className="main-layout">
        <Header />
        <div className="main">{props.children}</div>
      </div>
      <Outlet />
    </>
  )
}

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