
What's up guys, here is another "Today I Learned" session.
If you saw my first post of this series, you will remember I talked about a way to pass props down from a parent component to a Route@react-router (A child component).
Not long ago, I talked to my friend and he showed me a much cleaner way to complete this job. But what needed is a better understanding of the react-router-dom library. But no worries, you will get it once you see the explanation.
Without further ado, here is the solution:
Say, you want your component to receive RouterProps
, but don't want to wrap it in <Route component={ChildComponent}>
(which is exactly the way I talked about in the previous post).
You can just use withRouter
function to connect the "ChildComponent" component to the router, without additional manipulations or JSX tags wrapping. This looks much cleaner!
withRouter
function on react-router-dom documentation:
You can get access to the history object’s properties and the closest < Route>'s match via the withRouter
higher-order component. withRouter
will pass updated match, location, and history props to the wrapped component whenever it renders.
So, it seems like I get better at this topic by a little bit today. I encourage you, my friend, to do so.
Cheers!