Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 array.map() to generate a list of NavLink :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array.map(item => {
        return <NavLink key={item.id} to={routers.category+item.slug}>
            {item.slug}
        </NavLink>
    }
)

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)}

array.map(item => {
        return <NavLink key={item.id} to={routers.category.replace(':slug', item.slug)}>
            {item.slug}
        </NavLink>
    }
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading