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
components:
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?
3
Answers
You are using a hard coded string, the slug will not be replaced.
you can use backticks.
In my opinion, if you change your routes object structure your problem is solved. You can separate pathnames from routes.
For example:
Then your routes object something like the below:
Then you can solve your problem:
The issue is that for the link target you are using string concatenation.
This results in link targets like
"/category/:slug" + "chair"
which results in string literals"/category/:slugchair"
which likely isn’t what you expected or have a route path to match.react-router
exports a path generating utility, oddly enough, namedgeneratePath
.Use
generatePath
to take the"/category/:slug"
path and theslug
param to generate the target path.The
slug
property onitem
will be assigned to the":slug"
route path param.