react-router: Three route rendering methods (component, render and child)
Introduction
In the last post I talked about the setup tutorial react-router… If you haven’t read the previous post, click here! I want to add a few important topics about route rendering techniques.
Route rendering methods
There are several ways to render an HTML component or tag using
<Route path="https://habr.com/">
<Home />
</Route>
There is nothing wrong with this snippet and the
1. Component method
The first rendering method is very simple. We just need to place the component as a props in Route.
<Route path="https://habr.com/" component={Home} />
const Home = (props) => {
console.log(props);
return <div>Home</div>;
};
That’s all. You will get these props.
Wait. How can we pass another prop to the component? The answer is that we cannot use this rendering method. However, we can use render and children
2. Rendering method
By using this render method, you will have access to using the inline function, and you can pass another props to your component. Optionally, you can pass the route props as a function parameter.
<Route
path="/contact"
render={(routeProps) => {
return <Contact name={name} address={address} {...routeProps} />;
}}
/>
Via <Route render/>
you can also render an HTML tag without the need to render a component like <Route component/>
…
<Route
path="/contact"
render={() => {
return (
<div>
<h2>Contact</h2>
<p>Name: {name}</p>
<p>Adress: {address}</p>
</div>
);
}}
/>
I personally prefer to use this rendering method.
3. Child method
Basically, child and render methods are the same. They both receive a function, but if you use a child method, it will be rendered when the path does not match. You should also make sure that you are not using <switch>
…
<Route path="https://habr.com/" exact component={Home} />
<Route path="/about" render={() => <About></About>} />
<Route path="/portfolio" children={() => <Portfolio></Portfolio>} />
<Route path="/contact" children={() => <Contact></Contact>} />
In this case, when users encounter /
, Components <Portfolio/>
and <Contact/>
will be rendered as they use the child renderer. To be honest, I don’t know when this method should be used in a real project, but you can look at the documentation here…
Conclusion
There are three route rendering methods that you can use. At first I was puzzled as to why there are so many ways to render a route. After reading the documentation a few times, the “AHA” moment came.
I hope this was helpful and please leave comments for questions or feedback! Happy coding!
Translation of the material prepared as part of the course “React.js Developer”… If you are interested in learning more about the course, register on Open Day online, where the teacher will talk about the format and program of training.