ReactJs this.props.router undefined

15,691

You are missing a constructor method with a call to super(). super() calls the constructor of the parent class and is needed to properly pass the properties of the parents class to this component. You would need this to access any properties passed to the component, including router.

The top of your layout class should look like this.

export default class Layout extends React.Component {
  constructor(props) {
    super(props)
  }

  navigate() {
    ...
  }

  render() {
    ...
  }
}

Here are the docs on how classes work in ES6!

Edit 1: React Router

You also need to use the new withRouter when doing navigation via this.props.router. You do this by passing your component as an argument and exporting that. The withRouter function just wraps your component in another component that passes the router prop down to your component. I should point out that there are other ways of doing programmatic routing (singletons, context, etc.), but when using this.props.router.push you will need to use withRouter.

import { withRouter } from 'react-router' 
class Layout extends React.Component {
  constructor(props) {
    super(props)
  }

  navigate() {
    ...
  }

  render() {
    ...
  }
}

export default withRouter(Layout)

Using withRouter

Share:
15,691
August
Author by

August

Updated on June 23, 2022

Comments

  • August
    August almost 2 years

    Hello I am learning React js and I have came across a problem. When I try to change back to the main page using react router i get the following error:

    Uncaught TypeError: Cannot read property 'push' of undefined

    Here is my code, as you can see I am calling the navigate function:

    enter image description here

    My client.js with router:

    enter image description here

    If I replace this.props.router.push('/'); with this.props.history.push('/'); it works fine. What could be the problem?

  • August
    August about 8 years
    I have added constructor function but it's still saying the same error
  • August
    August about 8 years
    Yes i just changed the photo
  • August
    August about 8 years
    Thank you so much :), it works after i added export default withRouter(Layout)
  • TimoSolo
    TimoSolo over 7 years
    Why does no one tell you about withRouter?!?! been googling for days :D
  • Harkirat Saluja
    Harkirat Saluja over 7 years
    I can still use browserHistory.push right? Can tell difference between this.props.router.push and browserHistory.push ?