Search code examples
reactjsreact-routerreact-router-v4browser-historyreact-proptypes

react-router, The prop `history` is undefined


in my React App I am using react-router-dom and in one of the components after a function is triggered I want to route to Homepage. but I get the error

The prop `history` is marked as required in `GameElements`, but its value is `undefined`.
    in GameElements (created by Connect(GameElements))

and of course after call Uncaught TypeError: Cannot read property 'push' of undefined

this is my index.js

ReactDOM.render(
  <BrowserRouter>
    <Provider store={store}>
      <Route component={App} />
    </Provider>
  </BrowserRouter>,
  document.getElementById("root")
);

from homepage I got to the component like this

<Button color="blue" as={Link} to="/GameInit">
  START GAME
</Button>

now from GameInit I want to get back to HomePage like this

  cancel = () => {
    const { history, cancelGame } = this.props;
    cancelGame();
    history.push("/HomePage");
  };

GameElements.propTypes = {
  cancelGame: PropTypes.func.isRequired,
  history: PropTypes.shape({
    push: PropTypes.func.isRequired
  }).isRequired,
};

cancel game works and its reducer manipulates state as it should


Solution

  • wrap you GameElements is withRouter hoc, include it in your file

    import { withRouter } from 'react-router'
    

    Now at the bottom, where you export your component do this.

    export default withRouter(Connect(GameElements));
    

    You can read more here in the docs.