Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router v4 - How to get current route?

I'd like to display a title in <AppBar /> that is somehow passed in from the current route.

In React Router v4, how would <AppBar /> be able to get the current route passed into it's title prop?

  <Router basename='/app'>     <main>       <Menu active={menu} close={this.closeMenu} />       <Overlay active={menu} onClick={this.closeMenu} />       <AppBar handleMenuIcon={this.handleMenuIcon} title='Test' />       <Route path='/customers' component={Customers} />     </main>   </Router> 

Is there a way to pass a custom title from a custom prop on <Route />?

like image 976
Raphael Rafatpanah Avatar asked Feb 15 '17 15:02

Raphael Rafatpanah


People also ask

How do I listen to route changes in React v6 router?

Use your router and pass your history object to it. In a component you want to listen to location changes on, import your history object and invoke the listen callback as you did previously. import history from '../myHistory'; ... useEffect(() => { const unlisten = history.


2 Answers

In the 5.1 release of react-router there is a hook called useLocation, which returns the current location object. This might useful any time you need to know the current URL.

import { useLocation } from 'react-router-dom'  function HeaderView() {   const location = useLocation();   console.log(location.pathname);   return <span>Path : {location.pathname}</span> }  
like image 86
joy08 Avatar answered Sep 22 '22 08:09

joy08


In react router 4 the current route is in - this.props.location.pathname. Just get this.props and verify. If you still do not see location.pathname then you should use the decorator withRouter.

This might look something like this:

import {withRouter} from 'react-router-dom';  const SomeComponent = withRouter(props => <MyComponent {...props}/>);  class MyComponent extends React.Component {   SomeMethod () {     const {pathname} = this.props.location;   } } 
like image 38
Con Posidielov Avatar answered Sep 24 '22 08:09

Con Posidielov