Reputation: 21
I have loaded the dynamic category data by using redux and data is as follows:
const categories = [
{ id: 1, name: 'Luxury Boats', url: 'luxury-boat-hire' },
{ id: 2, name: 'Super Yacht Hire', url: 'super-yacht-hire' },
{ id: 3, name: 'Whitsundays', url: 'luxury-boat-hire-whitsundays' },
{ id: 4, name: 'New Years Eve Cruises', url: 'new-years-eve-cruises' }
];
I created one component with name of Category.js . I have to write the Router code to override the URL. As per router
<Router path=”/category/:id” exact component={Category} />
When I use the NavLink and write the code to design NavBar then I used the following code.
{
Categories.map(category => {
return <NavLink to={`/category/${category.id}`}>{category.name}</NavLink>
});
}
Above code create the 4 url for 4 categories like
Id:1 => http://localhost:3000/category/1
Id:2 => http://localhost:3000/category/2
Id:3 => http://localhost:3000/category/3
Id:4 => http://localhost:3000/category/4
But I want to make a URL like follows and also want to get id params in Category.js component
Id:1 => http://localhost:3000/category/1 => http://localhost:3000/luxury-boat-hire
Id:2 => http://localhost:3000/category/2 => http://localhost:3000/super-yacht-hire
Id:3 => http://localhost:3000/category/3 => http://localhost:3000/luxury-boat-hire-whitsundays
Id:4 => http://localhost:3000/category/4 => http://localhost:3000/ new-years-eve-cruises
if I will pass category.url instead of category.id then how may I get Id property in Category.js component to fetch category details and all products associated to this category? I want to get id params in Category component and URL also in SEO friendly.
passing props={category.id} is possible for that pages which has fix URL. URL is change for each page and category data is loading from json data from mysql database. I read your posting and you have fixed URL /aboutus only. but in my case all URL and category name and ID loading from database.
when I use the following code to pass id to Category component then URL is working first time but when we refresh the page then categoryid become empty:
to={{
pathname: props.link,
categoryid: props.id
}}
Please help to write a code for this
Upvotes: 2
Views: 2915
Reputation: 358
Just map to the url rather than category.id
{
Categories.map(category => {
return <NavLink to={`${category.url}`}>{category.name}</NavLink>
});
}
Upvotes: 1