In short: I want to show the slug instead of the Id in the URL, whats the best way to do that?
In my app.js component I am using React-router this way so far:
<Router history={browserHistory}>
<Route path="/" component={Main}>
<IndexRoute component={Home}></IndexRoute>
<Route path="/profile/:slug" component={Split}></Route>
</Route>
</Router>
Then in my profile component I am using Link to go to that specific profile via the slug:
<Link to={'/profile/' + username.slug}>{username}</Link>
I was thinking of keying them together in my profile reducer or something?
Any tips would be very helpful!
Redirect and Navigate Component With the release of React Router v6, the Redirect component was removed and replaced with the Navigate component, which operates just as the Redirect component does by taking in the to prop to enable you redirect to the page you specify.
Use the useParams() hook to get the ID from a URL in React, e.g. const params = useParams() . The useParams hook returns an object of key-value pairs of the dynamic params from the current URL that were matched by the Route path. Copied!
The best way I have found to do this is to have two objects within your state, one is users keyed by user id, the other is a slug-id lookup, keyed by slug. Say your users look like this:
{
_id: 1234
username: 'Mary Poppins',
slug: 'mary-poppins',
likes: [ 'umbrellas' ]
}
Then your state would look like:
{
users: {
1234: {
username: 'Mary Poppins',
slug: 'mary-poppins',
likes: ['umbrellas']
}
},
slugs: {
'mary-poppins': 1234
}
}
Now when you are rendering Link
components, you use:
<Link to=`/profile/${user.slug}`>{user.username}</Link>
And to select the user when you have the slug, you would have a selector such as:
const user = ( slug ) => ( state ) => state.users[state.slugs[slug]];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With