10

How can I get the current path using react router v4?

I have tried the following to no avail:

const currentLocation = this.props.location.pathname;

Error: Cannot read property 'pathname' of undefined

Here is my Routes.js file:

import React, {Component} from 'react';
import {  BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { Provider } from 'react-redux';
import configureStore from './Store';
import LevelOne from './containers/LevelOne';
import LevelTwo from './containers/LevelTwo';
import LevelThree from './containers/LevelThree';
import CreateProfile from './containers/Profile/CreateProfile';
import WhosWatching from './containers/Profile/WhosWatching';
import ProfileNameAvatar from './containers/Profile/ProfileNameAvatar';
import FavouriteGenres from './containers/Profile/FavouriteGenres';
import FourZeroFour from './containers/404';

import Header from './components/Header';

const store = configureStore();

const navItems = [
  {
    title:"For You",
    to: "/for-you"
  },
  {
    title:"Movies",
    to: "/movies"
  },
  {
    title:"Series",
    to: "/series"
  },
  {
    title:"TV Shows",
    to: "/tv-Shows"
  },
  {
    title:"Subscriptions",
    to: "/subscriptions"
  },
  {
    title:"Live TV",
    to: "/live-tv"
  }
]

export default class Routes extends Component {
  state = {
    theme: 'light'
  }

  header = React.createRef();

  setTheme = (theme) => {
    this.setState({
      theme: theme,
    });
  }

  render() {
    const currentLocation = this.props.location.pathname;
    console.log("location", currentLocation);
    return (
      <Provider store={store}>
        <Router ref='router'>
          <div className='app'>
            {/*<Header navItems={navItems} theme={this.state.theme} ref={this.header} />*/}
            <Switch>
              <Route exact path="/" render={(props) => (
                <LevelOne {...props} setTheme={this.setTheme} />
              )}/>
              <Route exact path="/for-you" render={(props) => (
                <LevelTwo {...props} setTheme={this.setTheme} />
              )}/>
              <Route exact path="/for-you/view-all" render={(props) => (
                <LevelThree {...props} setTheme={this.setTheme} innerRef={this.header} />
              )}/>
              <Route exact path="/profile/create-profile" render={(props) => (
                <CreateProfile {...props} />
              )}/>
              <Route exact path="/profile/whos-watching" render={(props) => (
                <WhosWatching {...props} />
              )}/>
              <Route exact path="/profile/profile-name-avatar" render={(props) => (
                <ProfileNameAvatar {...props} />
              )}/>
              <Route exact path="/profile/favourite-genres" render={(props) => (
                <FavouriteGenres {...props} />
              )}/>
              <Route component={FourZeroFour} />
            </Switch>
          </div>
        </Router>
      </Provider>
    );
  }
}
Filth
  • 3,116
  • 14
  • 51
  • 79

4 Answers4

21

You will only have access to this.props.location in a Route component (as the prop is passed to the component from it).

You can get the current path with window.location.pathname outside of the Router, though it's likely that you are doing something wrong if you are accessing the path here.

For children of Router, you can access the location by wrapping it around withRouter or pass the prop downwards from a Route component.

Redux integration will also allow you to access the location from anywhere.

Roy Wang
  • 11,112
  • 2
  • 21
  • 42
11

Fast solution
Create a variable on your function:

var currentLocation = window.location.pathname;

and then in the ul > li className={(currentLocation == '/' ? 'active' : '')}

it worked for mee and is a quick solution.

ingpedrorr
  • 165
  • 1
  • 4
4

this.props.match.path should do the trick

Jonathan.Brink
  • 23,757
  • 20
  • 73
  • 115
Steve Bohmbach
  • 327
  • 1
  • 11
  • Thanks for your answer, I replaced the currentLocation const with your suggestion and got an error with: Cannot read property 'path' of undefined – Filth May 24 '18 at 13:57
  • Sorry, my command was ment to be used inside of the Router Component i believe – Steve Bohmbach May 24 '18 at 14:05
3

you can get the path directly from the document variable.

eg: const path = document.location.pathname

rudresh solanki
  • 925
  • 9
  • 4