Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react router this.props.location

Tags:

I need a help with react-router v2+ I have to change class of navbar when route changed for example for route /profile className will be "profile-header" I tried to use this.props.location in navbar component but it shows undefined

Hope your help

like image 496
Андрей Гузюк Avatar asked Feb 02 '17 18:02

Андрей Гузюк


People also ask

How do I access location react router?

You can use useHistory , useLocation and useRouteMatch in your component to get match , history and location . You can use withRouter HOC in order to inject match , history and location in your component props. You can use withRouter HOC in order to inject router , params , location , routes in your component props.

How do I access react router props?

Another way to access the router props is to add an import statement at the top of the component and import 'withRouter'. import { withRouter } from 'react-router-dom'; Then in the export default statement at the end of the component you would wrap the component in 'withRouter'.

How do I use location pathname in react?

If you need to access the path, use window. location. pathname . The pathname property returns a string containing the path of the URL for the location.

Which props should you use to match exactly the path you have for routing?

The exact prop is used to define if there is an exactly the requested path.


2 Answers

Your navbar component (as you described it in your question) is probably not the route component, right? By route component I mean the one that you use in your react-router configuration that is loaded for a specific route.

this.props.location is accessible only on such route component, so you need to pass it down to your navbar.

Let's take an example:

Your router config:

<Router>     <Route path="/" component={App}>     // ... </Router 

Route component App:

class App extends React.Component{   // ...   render() {     return <Navbar location={this.props.location}/>   } } 
like image 125
szymonm Avatar answered Sep 18 '22 17:09

szymonm


There could be a scenario where you may not have access to props.location to pass to the nav component.

Take for example - We had a header component in our project which was included in the routing switch to make it available to all routes.

<Switch>   <Fragment>     <Header/>     <Route path='..' component={...}/>     <Route path='..' component={...}/>   </Fragment> </Switch> 

In the above scenario there is no way to pass the location data to the Header component.

A better solution would be to us the withRouter HOC when a component is not being rendered by your router. You will still have access to the router properties history, match and location when you wrap it in the withRouter HOC:

import { withRouter } from 'react-router-dom' ....  .... export default withRouter(ThisComponent) 
like image 29
varoons Avatar answered Sep 16 '22 17:09

varoons