Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go up one level in React-Router using Link

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.

like image 815
Jose A Avatar asked Apr 25 '19 21:04

Jose A


People also ask

How do I use router link in React?

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.

How does React router Dom link work?

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.

Can you pass props in link React router?

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 .

Can you style a React router link?

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.


1 Answers

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(".");
like image 142
Yevgeniy Timchenko Avatar answered Nov 06 '22 02:11

Yevgeniy Timchenko