How to pass props to React routes components
One of the ways to handle navigation in React applications is using
react-router and it is pretty easy to use, let's see an example:
But, what happens if we want to pass a prop to our component? Let's suppose we want to pass the current step to each component, so, probably we will be tempted to do something like the following:
It sounds like a good solution, isn't it? mmm, NO. With the previous code we are passing a prop called
Route component but not to
StepTwo component so we weren't able to see the current step in our components.
What can we do? Basically, we should change our approach, instead of use
component attribute, we should use
render attribute, and give it a try:
Ok, it looks better, probably if we check
StepTwo props, we have now
currentStep but wait!!! Now navigation does not work!!! This happens because of lack of route's props inside our component. We need a new change to pass route's props to the components:
Now we are able to pass props to our components and navigation will work as expected.
react-router is an easy and potent way to handle navigation in our React apps, the only thing we should take into account is that it should be tailored to our requirements, sometimes the easy/quick/happy way is not the best way.
If you like this story clap as many times as you want and to see similar stories about technology, check our publications and feel free to contact us for any question.