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

17,448

Solution 1

I would just do it with the way you have set up your route and then as you're using redux (because you said you were before edits) I would use mapStateToProps to filter or however it is you are passing the details as props.

for example:

const mapStateToProps = (state, ownProps) => {
  user: state.users.items.filter(user => user.slug === ownProps.params.slug),
}

Solution 2

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]];
Share:
17,448
DbTheChain
Author by

DbTheChain

Updated on June 05, 2022

Comments

  • DbTheChain
    DbTheChain almost 2 years

    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!

  • Mel
    Mel over 4 years
    I understand the logic to this. If it's unsafe to show the user id in the route url - is this a standard way to overcome that or is there a newer convention?