3
votes

How do I populate context so that history is not undefined when using tags in react-router?

The error I am getting is : Uncaught TypeError: Cannot read property 'pushState' of undefined

on function Link.handleClick at line:

if (allowTransition) this.context.history.pushState(this.props.state, this.props.to, this.props.query);

I'm using react-router 1.0.0-rc1.

The top level routes works fine. I get to my main component, which displays a link to "signup". This link should bring me to the child component.

My sample app looks like this:

Routes.jsx
============
var React = require('react');
var ReactRouter = require('react-router');
var createBrowserHistory = require('history/lib/createBrowserHistory');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;

var Main = require('./main/main');
var Signup = require('./signup/signup');

module.exports = (
   <Router history ={createBrowserHistory()}>
     <Route path="/app" component={Main}>
       <Route path="/signup" component={Signup}></Route>
     </Route>
   </Router>
);

Main.jsx
===============
var ReactRouter = require('react-router');
var Link = ReactRouter.Link;
module.exports = React.createClass({
  render: function(){
      return <div><Link to="/signup">signup</Link></div>
  }
})
1
same Error was for me but I was get solution by this.props.history.push('/', null); and check it by this.props.history YOu should be get to see also push and replace bothfunctionMD Ashik

1 Answers

0
votes

I was having this same problem. Ensure that your <Router> definition is at your top level and not embedded within another Component.

My version that is working:

var React = require('react');
var ReactDOM = require('react-dom');
var {useBasename, createHistory} = require('history');
var routes = require('./routes/routes');
var {Router} = require('react-router');

const history = useBasename(createHistory)({
  basename: '/'
})

  ReactDOM.render(
    <Router history={history}>
      {routes}
    </Router>,
    document.getElementById('app'));

My routes.js file:

var React = require('react');
var { IndexRoute, Router } = require('react-router');
var Route = require('react-router').Route;
var AppContainer = require('../components/AppContainer');
var Index = require('../components/Index');
var Login = require('../components/Login');
var Register = require('../components/Register');

module.exports = (
  <Route path="/" component={AppContainer}>
    <IndexRoute component={Index} />
    <Route path="register" component={Register} />
  </Route>
);