Bellicose Agnostic
Bellicose Agnostic

Reputation: 76

React ES6 Class transitionTo Not Working

Inside Class

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

someFn = () = {    
    this.context.router.transitionTo('google.com');
}

at the bottom of component

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

I keep getting the error Warning: Failed Context Types: Required context router was not specified in Homepage.

When I click on the button to navigate I get the following additional error Uncaught TypeError: Cannot read property transitionTo of undefined

I've even tried adding the following in the constructor but to no avail

this.context = context

Upvotes: 0

Views: 1882

Answers (3)

STEEL
STEEL

Reputation: 10017

The vast majority of applications do not need to use context. (ref: https://reactjs.org/docs/context.html)

Below should help you =>

import {Component} from 'react';
import PropTypes from 'prop-types';

class MyComponent extends Component {

  static contextTypes = {
    router: PropTypes.object
  };

  onFormSubmit() {
    this.context.router.push('/home');
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit.bind(this)}>
      </form>
    );
  }
}

Upvotes: 1

Kohei TAKATA
Kohei TAKATA

Reputation: 81

I tried below and worked correctly. My react-router is 1.0.0-rc3.

export default class MyComponent extends React.Component {
    static contextTypes = {
        history: React.PropTypes.object
    }
    routeHandler() {
        this.context.history.pushState(null, '/test');
    }
    render() {
        return <button onClick={this.routeHandler.bind(this)} />;
    }
}

Upvotes: 0

Bellicose Agnostic
Bellicose Agnostic

Reputation: 76

I asked the same question in react-router github repo and got the answer https://github.com/rackt/react-router/issues/2107

the gist: history is replacement for old router

class Component extends React.Component {
  static contextTypes= {
    history: React.PropTypes.object,
    location: React.PropTypes.object
  }
  render() {
      console.log(this.context.history, this.context.location)
      return null;
  }
}

Upvotes: 0

Related Questions