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