Search code examples
reactjsundefinedpathname

React ocation.pathname typerror: Cannot call location.pathname in one file, but can in other file


In one of my Components, I can easily call a "this.props.location.pathname". But when I try this in another component I get

TypeError: Cannot read property 'pathname' of undefined

And I can't seem to find out what is different..

WORKS:

import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';

export default class RedirectUser extends Component  {
    render () {
        return (
            <span className='redirecting'>
                {this.props.location.pathname === '/' || this.props.location.pathname === '/mgmt' || this.props.location.pathname === '/mgmt/' ?
                    <Redirect to='/mgmt/entrepreneurs' />
                : this.props.location.pathname === '/user' || this.props.location.pathname === '/user/' ? 
                    <Redirect to='/user/settings' />
                : this.props.location.pathname === '/dev' || this.props.location.pathname === '/dev/' ? 
                    <Redirect to='/dev/story' />
                : null
                }
            </span>
        );
    }
};

DOESN'T WORK

import React, { Component } from 'react';
import { NavLink, Link } from 'react-router-dom';
import Icon from '../library/icons/Icon';
import '../App.css';
import { UserConsumer } from '../App.js';
import ProfilePicture from '../library/imgs/examples/profilepic.jpg';

export default class MainNavigation extends Component  {
    constructor (props) {
        super (props)
        this.state = {
            nav: this.props.location.pathname === '/mgmt' ? 
                    'management' 
                :this.props.location.pathname === '/social' ? 
                    'social' 
                :this.props.location.pathname === '/work' ?
                    'work'
                :this.props.location.pathname === '/dev' ?
                    'dev'
                : 'management',
            navFloat: false,
            greeting: '',
            mobileMenu: false
        }
        this.closeNavTab = this.closeNavTab.bind(this);
    }
...
...

Solution

  • Your navigation component is not a route component. [Component that you use in your react-router configuration against a route]

    I'm guessing RedirectUser component is one such component

    e.g

    <Route path='...' component={RedirectUser}/>
    

    Only these components have access to this.props.location.

    You will need to pass the prop to your navigation component or as @jens suggests use the withRouter HOC with MainNavigation

    import { withRouter } from 'react-router-dom'
    .... 
    ....
    export default withRouter(MainNavigation)