samolex
1
I am trying to make a tiny component to display the path in my e-commerce app.
I can make it to work using plain javascript, but I’ve got no idea how to do it and make react-router aware.
what i have so far:
const RouteBar = ({ location, ...props }) => {
console.log(props);
const [path, setPath] = useState([]);
useEffect(() => {
const path = location.pathname.split('/').filter(Boolean);
setPath(path);
}, [location.pathname]);
console.log(path);
const renderPath = path.map((url, index) => {
return (
<Fragment key={generateId()}>
<Link
to={`${window.location.origin}/${path.join('/')}`}
>
{url}
</Link>
</Fragment>
);
});
I have even tried the replace
prop on Link
, but it’s not doing what i want.
Hi @samolex,
I guess you can import the useLocation hook from react-router.
import {useLocation} from "react-router-dom";
const RouteBar = () => {
const location = useLocation();
return <div>{location.pathname}</div>
}
samolex
3
sure! I have done that.
What I want is that if I have the links from the array:
shop / product / anything
…on clicking on any link (anything) from the above links I should be directed to its path. eg.
clicking on:
shop => http://localhost:3000/shop
product=> http://localhost:3000/shop/product
In this case:
const RouteBar = () => {
const links = [{
name: 'Shop',
path: '/shop'
},
{
name: 'About',
path: '/about'
},
]
return links.map(link => <Link key={link.name} to={link.path}>{link.name}</Link >
}
samolex
5
OMG. I am too dumb not to have thought of this. Thank you!
@samolex, don’t say that 
Sometimes you just need a second pair of eyes.