Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
        );
      }
like image 201
Emo Avatar asked Nov 12 '15 15:11

Emo


People also ask

What is pushState in Javascript?

pushState() method adds an entry to the browser's session history stack.

What is html5 pushState?

This API allows you to manipulate the browser history via script. You can change the URL in the browser without triggering a page refresh, and also listen for when a user presses the back button.

What is history push ()?

history. push() is another approach where we make use of the history props React Router provides while rendering a component. In other words, this works when the component is being rendered by React Router, bypassing the component as a Component prop to a Route.


1 Answers

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() {
  this.props.changeRoute(null, 'somepath', {query: "something"});
}

React Router v.2

import {browserHistory} from 'react-router';

//SomeComponent

browserHistory.push('somepath');
like image 135
Emo Avatar answered Sep 23 '22 20:09

Emo