Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current route in react-router 2.0.0-rc5

I have a router like below:

<Router history={hashHistory}>     <Route path="/" component={App}>         <IndexRoute component={Index}/>         <Route path="login" component={Login}/>     </Route> </Router> 

Here's what I want to achieve :

  1. Redirect user to /login if not logged in
  2. If user tried to access /login when they are already logged in, redirect them to root /

so now I'm trying to check user's state in App's componentDidMount, then do something like:

if (!user.isLoggedIn) {     this.context.router.push('login') } else if(currentRoute == 'login') {     this.context.router.push('/') } 

The problem here is I can't find the API to get current route.

I found this closed issue suggested using Router.ActiveState mixin and route handlers, but it looks like these two solutions are now deprecated.

like image 914
wxtry Avatar asked Jan 27 '16 08:01

wxtry


People also ask

How do I get the current route in my React router?

Use the useLocation() hook to get the current route with React Router, e.g. const location = useLocation() . The hook returns the current location object. For example, you can access the pathname as location. pathname .

How do you find the route of a parameter React?

To get path params in React Router, we can use the useParams hook. We create the Child component that calls the useParams hook to return an object with the route params in the URL. And we render the value of the id param on the page. In App , we have 2 links that goes to routes with different id param values.

How do I check React route version?

We can verify the React version by directly visiting the package. json file and see the React app version at dependencies: {} section as given below. { ... ... ... "name": "react-app", "version": "0.1. 0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.


2 Answers

After reading some more document, I found the solution:

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md

I just need to access the injected property location of the instance of the component like:

var currentLocation = this.props.location.pathname 
like image 59
wxtry Avatar answered Sep 22 '22 11:09

wxtry


You can get the current route using

const currentRoute = this.props.routes[this.props.routes.length - 1]; 

...which gives you access to the props from the lowest-level active <Route ...> component.

Given...

<Route path="childpath" component={ChildComponent} /> 

currentRoute.path returns 'childpath' and currentRoute.component returns function _class() { ... }.

like image 37
colllin Avatar answered Sep 22 '22 11:09

colllin