An unopinionated way to get dynamic routes in React
Hi, this is going to be a relatively short article. In it, i'm going to show the way I get dynamic routes in my React apps. If you've heard of dynamic routes they are basically routes or parts of routes that aren't hard coded in, the path is dynamically injected.
// hard coded route
<Route path="/hashnode/username" render={<p>Hi</p>} />
//dynamic route
<Route path="/hashnode/:username render={<p>Hi</p>} />
So via the dynamic route you can navigate to /hashnode/timothy
or /hasnode/thomas
etc it'll all work.
So now if you wanted to get :username
, assuming the path is /hashnode/timothy
in React you'd have to go
props.match.params.username //returns timothy
or alternatively you could go:
const {match} = props;
const {username} = match.params;
//returns timothy
And that's fine really but what if you or someone on your team changes it from :username
to user
? then you have to go to the file where you got the dynamic route and change it to user too because the property username
no longer exists. If you don't that part of your app breaks.
The code below is an unopinionated way I get dynamic routes in my applications, unopinionated in the sense that it does not care what the name of the dynamic route is, it will always be able to get it regardless.
Object.keys(props.match.params).map(el=> props.match.params[el]).join('')
There you have it, ! Hope you enjoyed this article and until next time, be well.
Subscribe to my newsletter
Read articles from timothy ogbemudia directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by