erp
erp

Reputation: 3014

Get path name of route globally in react

I have a basic routing SPA working using react-router-dom v4 and I would like to get the current route (path name) for use in my header (outer context of the app - not sure if that's accurate nomenclature). I want to have a button in my app bar which will do something depending on the route currently in use.

index.js

ReactDOM.render((
  <MuiThemeProvider>
    <div>
      <Router history={history}>
        <div>
          <Header />
          <MainView />
        </div>
      </Router>
    </div>
  </MuiThemeProvider>
), document.getElementById('app'));

header.js

class Header extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      open: false
    };
  }

  toggleDrawer(){
    this.setState({open: !this.state.open}, ()=> {console.log(this.state)});
  }

  render() {
    return (
      <div>
        <AppBar
          iconClassNameRight="muidocs-icon-navigation-expand-more"
          onLeftIconButtonTouchTap={()=>{this.toggleDrawer()}}
          iconElementRight={<FlatButton label="Create New"/>}
        />

        ...

In the header.js I want access to the route's pathname to call a certain function from the <FlatButton /> on the right of the appbar. I've tried {this.props.location.pathname} as per the v4 docs but only got errors. TBH I was probably using it wrong though.

Upvotes: 3

Views: 2626

Answers (2)

Brandon
Brandon

Reputation: 39202

That prop is only provided to components rendered as the child of a Route. If you want it somewhere else (like in your Header), you can use the withRouter helper method to inject the props into your component:

// Header.js
import { withRouter } from 'react-router';

// private header class
class Header extends React.Component {
   render() {
      // you can access this.props.location here
   }
}

// wrap Header class in a new class that will render the
// Header class with the current location
// export this class so other classes will render this
// wrapped component
export default withRouter(Header);

// index.js
// ....
ReactDOM.render((
  <MuiThemeProvider>
    <div>
      <Router history={history}>
        <div>
          <Header />
          <MainView />
        </div>
      </Router>
    </div>
  </MuiThemeProvider>
), document.getElementById('app'));

Upvotes: 3

Jesus Mendoza
Jesus Mendoza

Reputation: 323

You should use react-router-dom if you are not using it (it's the default react-router package for the web now).

import { BrowserRouter, Route, Link } from 'react-router-dom';

ReactDOM.render((
  <MuiThemeProvider>
    <div>
      <BrowserRouter>
        <div>
          <Route component={Header} />
          <Route exact path="/" component={MainView} />
        </div>
      </BrowserRouter>
    </div>
  </MuiThemeProvider>
), document.getElementById('app'));

and then from the header.js try using

this.props.location.pathname

Upvotes: 2

Related Questions