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
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.
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'.
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.
The exact prop is used to define if there is an exactly the requested path.
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}/> } }
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)
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