Matt
Matt

Reputation: 8942

React-router: "Cannot read property 'transitionTo' of undefined"

I use webpack, ES6, react-router library and Link component for my links. I want to "transit" with parent div of link element, but when I click on div I get error:

Uncaught TypeError: Cannot read property 'transitionTo' of undefined

I followed this and this thread.

NavBar.jsx

var React = require('react');
var Router = require('react-router');
var { Route, DefaultRoute, RouteHandler, Link } = Router;

var CustomersIcon = require("./icons").CustomersIcon;

export class NavBar extends React.Component {

  constructor(props, context) {
      super(props, context);
  }

  _openLink() {
      this.context.router.transitionTo('/');
  }

  render() {
    return (
         <div className="menu-item-wrapper" onClick={this._openLink.bind(this)}>
             <CustomersIcon />
             <Link to="/customers" activeClassName="active" ref="customersLink">Customers</Link> 
          </div>
    );     
  }
}

NavBar.contextTypes = {
  router: function contextType() {
    return React.PropTypes.func.isRequired;
  }
};

Upvotes: 0

Views: 4499

Answers (5)

charlie
charlie

Reputation: 181

This answer provides the way to programmatically redirect with react-router 2.0.0.

Relevant bit:

import { browserHistory } from './react-router' browserHistory.push('/some/path')

Upvotes: 0

alexpods
alexpods

Reputation: 48485

router was removed from context in 1.0 version (see upgrade doc here) Now in context you have history and location (see here). Try this:

this.context.history.pushState(null, '/');
//...
NavBar.contextTypes = {
  history: React.PropTypes.object.isRequired,
};

Upvotes: 2

Alexandre Kirszenberg
Alexandre Kirszenberg

Reputation: 36408

Your code uses the old router API. The API changed a lot from 0.13 to 1.0.0RC.

You want to retrieve the history object from context:

NavBar.contextTypes = {
  history: React.PropTypes.object.isRequired,
};

And to transition to another url, from within a NavBar method:

this.context.history.pushState(null, '/');

See the History Mixin API.

You can also specify a more precise history contextType using the history propType exposed by the library:

var RouterPropTypes = require('react-router').PropTypes;

Navbar.contextTypes = {
  history: RouterPropTypes.history,
};

Upvotes: 4

knowbody
knowbody

Reputation: 8276

In the React Router 1.0 there is no router on the context anymore. It was replaced by location:

NavBar.contextTypes = {
  location: React.PropTypes.object
}

you can find more about the changes in the 1.0 version in the Upgrade Guide.

Also there is no transitionTo you would use history for that and do something like: this.history.pushState(null, '/somePath'). Definitely check the Upgrade Guide.

Upvotes: 0

kulesa
kulesa

Reputation: 2964

Your definition of contextTypes looks wrong. It should be

NavBar.contextTypes = {
  router: React.PropTypes.func.isRequired
};

Upvotes: 0

Related Questions