Reputation: 81
I have an error with the react-router-dom
I have one component that I'm rendering with the following:
<Route path='/categories/:url_type' component={Categories} exact />
Based on the url a different argument, either "following" or "all" , is passed into the react router and something different is rendered inside the component.
But there is an error: Whenever I want to render my component with the second argument "following" like this:
http://localhost:3000/categories/following
, the url of the site I previously accessed isn't cleared. So if I have been on a "profile" site, I would instead get this
http://localhost:3000/profile/categories/following
As a result, I get an error and nothing is rendered.
This is the link from where I access it in my html(Material UI):
const sections= [
{ title: 'All Categories', url: 'categories/all' },
{ title: 'Following', url: "categories/following"},
]
// I'm merging to arrays in my code, this is for simplicity
{sections.map((section)=>(
<Link component={RouterLink} to={section.url}>{section.link}</Link>
))}
This how I process the links. The function "allCategories()" definitely works:
useEffect(() => {
if (url_type === "all"){
allCategories("http://127.0.0.1:8000/api/category/")
}
else if (url_type === 'following'){
allCategories("http://127.0.0.1:8000/api/category/follow")
}
else {
history.push("/404")
}
}, []);
I've seen this post react router stacking url but I'm not sure how to implement the solution and if our problems are the same. Thank you a lot for your help!
Upvotes: 4
Views: 10761
Reputation: 553
React Router will treat paths that start with a slash as absolute paths. Here, your url
property in your sections
array are treated as relative paths because they don't start with a slash.
Just add a slash at the beginning of every path in your array:
const sections= [
{ title: 'All Categories', url: '/categories/all' },
{ title: 'Following', url: "/categories/following"},
]
Upvotes: 9