Reputation: 29
I am using the react-router-dom
and creating some routes in my application. Can anyone please explain me the specific usages of and . What will be the difference affect in the rendering if there are any. I will include a sample code snippet.
import { BrowserRouter as Router, Route } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Router>
<Route path="/home" component={App} />
<Route path='/about'>
<About />
</Route>
</Router>
);
I tried both and both are working fine. But I was unable to find the specific usage of one over other.
Upvotes: 1
Views: 554
Reputation: 987
Just a small add to Mr. Drew Reese's answer, the way rendering a component directly inside <Route>
allow you to freely pass your own props inside your component (it's more familiar to the way we usually do with normal React components).
Ex: You have a page About, inside, it includes 3 tabs: "About me", "About my team", "About my blog".
const About = () => {
// call APIs, handle...
return (
<>
<Switch>
<Route path='/about-me'>
<Me data={dataMe} />
</Route>
<Route path='/about-team'>
<Team data={dataTeam} />
</Route>
<Route path='/about-blog'>
<Blog data={dataBlog} />
</Route>
</Switch>
</>
)
}
Upvotes: 1
Reputation: 202751
The react-router-dom@5
Route
component has 4 ways to render content. The primary method is to directly render content as the children
prop. Note here that no route props will be passed to the component.
<Route path='/about'>
<About />
</Route>
The other 3 ways are to use one of the route render methods.
The recommended method of rendering something with a
<Route>
is to use children elements, as shown above. There are, however, a few other methods you can use to render something with a<Route>
. These are provided mostly for supporting apps that were built with earlier versions of the router before hooks were introduced.
Examples:
component
- Other common method, route props are implicitly passed as props to the component.
<Route path='/about' component={About} />
render
function - Alternative to pass along runtime props as well as the route props.
<Route path='/about' render={routeProps => <About {...routeProps} {...otherProps} />} />
children
function - Renders regardless of route match and passes route props to component to handle any conditional logic.
<Route path='/about' children={routeProps => <About {...routeProps} />} />
Upvotes: 2