<Router>
<Routes>
<Route path='/' element={<Navbar />} />
<Route path='/' element={<div className='recipes'>
{query ? query.map((object, i) => (
<RecipeCard
src={object.src}
ingredients={object.ingredients}
steps={object.steps}
key={i}
/>
)) : "Loading"}
</div>}/>
<Route path='/' element={<Details />} />
</Routes>
</Router>
For example in the above code, I want to render the HTML along with the Route element. I am not getting the 2nd and 3rd Route tags displayed on my localhost. Where is my mistake? What is the correct way to do this?
CodePudding user response:
The only requirement is that the element
prop takes a React.ReactNode
. In other words, it takes any valid JSX.
The issue though is that there can only be one route per path. Your code is trying to render 3 routes on the same "/"
path. Just unconditionally render the Navbar
and Details
components not on a route.
Example:
<Router>
<Navbar />
<Routes>
<Route
path='/'
element={(
<div className='recipes'>
{query
? query.map((object, i) => (
<RecipeCard
src={object.src}
ingredients={object.ingredients}
steps={object.steps}
key={i}
/>))
: "Loading"
}
</div>
)}
/>
</Routes>
<Details />
</Router>
If you are wanting to conditionally render Navbar
and Details
on only certain routes then create a layout route component.
Example:
import { Outlet } from 'react-router-dom';
const Layout = () => (
<>
<Navbar />
<Outlet /> // <-- nested routes render element content here
<Details />
</>
);
Render the routes you want to have the navbar and details as nested routes, and for the routes you don't want them render these as sibling routes.
<Router>
<Routes>
<Route element={<Layout />}>
<Route
path='/'
element={(
<div className='recipes'>
{query
? query.map((object, i) => (
<RecipeCard
src={object.src}
ingredients={object.ingredients}
steps={object.steps}
key={i}
/>))
: "Loading"
}
</div>
}
/>
...other routes with Navbar and Details...
</Route>
...other routes w/o Navbar and Details...
</Routes>
</Router>