user818700
user818700

Reputation:

react and react-router context undefined

I'm trying to navigate from one route to another, the way I've setup my routes:

App.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';

// Pages
import Layout from './pages/Layout/Layout';
import Home from './pages/Home/Home';
import CityOverview from './pages/CityOverview/CityOverview';
import Game from './pages/Game/Game';

ReactDOM.render(
    <Router history={hashHistory}>
        <Route path='/' component={Layout}>
            <IndexRoute component={Home}></IndexRoute>
            <Route path='/city-overview' component={CityOverview}></Route>
            <Route path='/game' component={Game}></Route>
        </Route>
    </Router>,
    document.getElementById('app')
);

I then try and do the navigation in this class:

import React from 'react';

class MyComponent extends React.Component {

    constructor () {
        super();
        this.state = {
            email : '',
            password : ''
        };
    }

    render () {
        // ...
    }

    navigate () {

        this.context.router.push('/city-overview');

    }

}

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

export default MyComponent;

However when this runs, I get a "context is undefined error"...

Upvotes: 1

Views: 923

Answers (2)

Mina Youssef
Mina Youssef

Reputation: 1

Use "props" instead of "context"

this.props.router.push("city-overview");

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281696

You need to bind the navigate function to the appropriate context so that this keyword inside it refers to the React class rather than the function . You can make use of arrow functions to do the same.

navigate = () => {

    this.context.router.push('/city-overview');

}

or else bind it in the constructor

constructor () {
        super();
        this.state = {
            email : '',
            password : ''
        };
        this.navigate = this.navigate.bind(this);
    }

Upvotes: 1

Related Questions