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:

Simple Router 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:

Attempting to pass a prop to Step component

It sounds like a good solution, isn't it? mmm, NO. With the previous code we are passing a prop called currentStep to Route component but not to StepOne or 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:

Changing approach to be able to pass props to Step component

Ok, it looks better, probably if we check StepOne or 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:

Final solution

Now we are able to pass props to our components and navigation will work as expected.

Wrapping up

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.

Gustavo
Mail: gustavo@alturasoluciones.com
Twitter: @Aguardientico
LinkedIn: www.linkedin.com/in/gustavoagonzalez
Blog in spanish: http://aguardientech.blogspot.com

Like what you read? Give Gustavo Gonzalez a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.