'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!



Solution 1:[1]

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]];

Solution 2:[2]

**//Server Side Communicate with frontend. Product data....**
const products = [
  {
    img:"https://cdn-images-fishry.azureedge.net/product/Krunch-500x360-a6056d0-kfc.png/xs",
    title:"Kuranch burger",
    discription:"Enjoy the crispy chicken fillet in a soft bun with spicy mayo and our signature sauce with fresh lettuce.",
    price:210,
    slug:"EVERYDAY-VALUE",
  },
  {
    img:"https://cdn-images-fishry.azureedge.net/product/Krunch-500x360-a6056d0-kfc.png/xs",
    title:"Kurnach burger",
    discription:"Enjoy the crispy chicken fillet in a soft bun with spicy mayo and our signature sauce with fresh lettuce.",
    price:200,
    slug:"EVERYDAY-VALUE",
  },


  ]

//then

app.get("/products/:slug", function (req, resp) {
  const slugs = req.params.slug;
  const pro = products.filter(p=>p.slug==slugs) 
  resp.send(pro);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex Young
Solution 2