How to merge a router have variable with variables in array in React

I have a config route :

const routers = {
  home: '/',
  category: '/category/:slug',

and an array :

array = [
      { id: 1, slug: 'table'},
      { id: 2, slug: 'chair'},

I use to generate a list of NavLink : => {
        return <NavLink key={} to={routers.category+item.slug}>

But it doesn’t work. The result is localhost:3000/category/:slugtable and localhost:3000/category/:slugchair.

The expected result is localhost:3000/category/table.

How can I solve it? Thanks.

>Solution :

Your appending to the string but it seems like you want to replace :slug with item.slug:

So use replace() to replace that part with item.slug:

to={routers.category.replace(':slug', item.slug)} => {
        return <NavLink key={} to={routers.category.replace(':slug', item.slug)}>

Leave a Reply