Surprisingly that it's been kind of hard to find in Google and in StackOverflow, I'm asking here what's the most efficient way on going up one level in React Router using <Link>
?
For example I land in this path: /subject/add
. Then I want to go to /subject
from /subject/add
.
This works:
<Link to={props.match.url.substring(0, props.match.url.lastIndexOf('/'))}>
Go up one level </Link>
Is it the best way to do it? (Note: history.goBack
could potentially kick out the user from the website if he arrived on a nested route as his landing page.
To add the link in the menu, use the <NavLink /> component by react-router-dom . The NavLink component provides a declarative way to navigate around the application. It is similar to the Link component, except it can apply an active style to the link if it is active.
A <Link> is an element that lets the user navigate to another page by clicking or tapping on it. In react-router-dom , a <Link> renders an accessible <a> element with a real href that points to the resource it's linking to. This means that things like right-clicking a <Link> work as you'd expect.
To recap, if you need to pass data from Link through to the new component that's being rendered, pass Link s a state prop with the data you want to pass through. Then, to access the Link s state property from the component that's being rendered, use the useLocation Hook to get access to location. state .
With styled-components, you can use component-level styles in applications that are written using CSS-in-JS. CSS-in-JS libraries like styled-components allow us to write CSS in JavaScript in a very elegant and reusable way by changing the way CSS styles are applied to React components.
If somebody still needs it - there is a solution from authors: You can use "." or ".." in your Link component to go one or two levels up.
<Link to=".">
or
history.push(".");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With