Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS- Use slug instead of Id in the URL with React router

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!

like image 289
DbTheChain Avatar asked Mar 07 '17 22:03

DbTheChain


People also ask

What can I use instead of Redirect in react router Dom?

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.

How does react JS read ID from URL?

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!


1 Answers

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]];
like image 97
Alex Young Avatar answered Oct 30 '22 23:10

Alex Young