Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required context `router` was not specified. Check the render method of `RoutingContext`

My app is ES6 React application with react-router. I want to redirect user to a different page after a small delay. Here is my React component:

import React from 'react'
import { Navigation } from 'react-router'

export default class Component extends React.Component {

    render () {
        return (
            <div>Component content</div>
        )
    }

    componentDidMount () {
        setTimeout(() => {
            // TODO: redirect to homepage
            console.log('redirecting...');
            this.context.router.transitionTo('homepage');
        }, 1000);
    }

}

Component.contextTypes = {
    router: React.PropTypes.func.isRequired
}

And react-router routing table:

render(
    <Router>
        <Route path='/' component={ App }>
            <IndexRoute component={ Component } />
        </Route>
    </Router>
, document.getElementById('app-container'));

The issue is that 'router' property is not passed into the component. Chrome console's content is:

Warning: Failed Context Types: Required context `router` was not specified in `Component`. Check the render method of `RoutingContext`.
redirecting...
Uncaught TypeError: Cannot read property 'transitionTo' of undefined

React version is 0.14.2, react-router version is 1.0.0-rc4 Where do I make mistake?

like image 830
Leo Toff Avatar asked Nov 09 '15 19:11

Leo Toff


1 Answers

Im not a react-router expert by any means, but I had the same issue earlier today. I am using React 0.14.2 and React-Router 1.0 (this just came out in the last couple of days, if not more recently). While debugging I noticed that the props on the React component includes history (the new style of navigation - https://github.com/rackt/react-router/blob/master/docs/guides/basics/Histories.md)

I am also using TypeScript, but my code looks like the following:

import React = require('react');
import Header = require('./common/header.tsx');

var ReactRouter = require('react-router');

interface Props extends React.Props<Home> {
    history: any
}

class Home extends React.Component<Props, {}> {
    render(): JSX.Element {
        return (
            <div>
                <Header.Header MenuItems={[]} />
                <div className="jumbotron">
                    <h1>Utility</h1>
                    <p>Click on one of the options below to get started...</p>
                    {<a className="btn btn-lg" onClick={() => this.props.history.pushState(null, '/remoteaccess') }>Remote Access</a>}
                    {<a className="btn btn-lg" onClick={() => this.props.history.pushState(null, '/bridge') }>Bridge</a>}
                </div>
            </div>
        );
    }
}

module.exports = Home;
like image 65
JTaub Avatar answered Sep 21 '22 08:09

JTaub