I'm trying to disable my Header and Footer components on my Product page. Here is my code:
const HeaderRoute = useCallback(
() =>
!["/create", "/sign-up", "/sign-in", "/product"].includes(
window.location.pathname
) && <Header />,
[]
);
However, my Product component url contains custom :id or path="/product/:id" :
<Route exact path="/product/:id" component={Product} />
The header doesn't render on the other urls, but it does on the /product:id url for some reason. Any ideas why?
The method includes searches for exact matches, so that ['/product'].includes('product') is false.
If you want to see if a string matches inside another you can use match.
Your condition will be like:
const HeaderRoute = useCallback(
() =>
!["/create", "/sign-up", "/sign-in", "/product"].some(path =>
window.location.pathname.match(path)
) && <Header />,
[]
);
function showHeader(pathname) {
return !["/create", "/sign-up", "/sign-in", "/product"].some(path => pathname.match(path));
}
console.log(showHeader("/product:id")); // false
console.log(showHeader("/create")); //false
console.log(showHeader("/create/new:id")); //false
console.log(showHeader("/anotherPage")); //true