Emo Emo - 7 months ago 78
Javascript Question

Cannot read property 'pushState' of undefined

I have this simple configuration for the React Router. I have another one with basically wrapping with ... , which works. But this one doesn't (of course I tried to use with different implementations like suggested in the answers of this post and many others.

The console error is the title of this post.
Using ES6, and react-router v.1 with hash-based routing.

I read a lot of articles, too unnecessary for simple routing to be implemented, and almost hating react and react-router now. Please help.

componentWillReceiveProps() {
this.contextTypes = {
history: React.PropTypes.object
}
},
_handleRoute(e) {
e.preventDefault()
this.history.pushState(null, `/somepath`);
},
render() {
return(
<div onClick={this._handleRoute}>
Some Content.
</div>
);
}


or:

render() {
return(
<div>
<Link to={`/somepath`}> link </Link>
</div>
);
}

Emo Emo
Answer

React Router v1:

There's the pushState method in history object made for this.

First the component assigned for router has to give the child component the pushState method as a function prop:

//Router Component
render ()
  return (
    <SomeComponent changeRoute={this.props.history.pushState}
  )

Then, in the Component that I want to change route in a function, I simply do:

//SomeComponent
onClick() {
  const location = this.props.location;
  this.props.changeRoute(null, location.pathname, {query: "something"});
}