angry_kiwi angry_kiwi - 2 months ago 15
React JSX Question

reactjs - can not read property push of undefined

I have this code. What I want to do is when I click a button 'feature' it will take me to index route. However, React keeps saying 'can not read property push of undefined' What I've done wrong?

route.js

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

import Layout from "./page/Layout";
import Features from "./page/Features";
import Features from "./page/archive";

const app = document.getElementById('app');

ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Layout}>
<IndexRoute component={Features} />
<Route path="archive" component={Archive} />
</Route>
</Router>, app);


Layout component

import React from "react";
import {Link, Router, Route, hashHistory} from "react-router";
export default class Layout extends React.Component{
navigate(){
this.context.router.push('/');
}
render(){
return(
<div>
{this.props.children}
<button onClick={this.navigate.bind(this)}>feature</button>
</div>
)
}
}


package.json - partial

"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.1"
"history": "^2.0.1",


-------------update to jordan's answer-------------

Answer
export default class Layout extends React.Component{

    navigate = () => {
        this.context.router.push('/');
    }
    render(){ 
        return(
            <div>
                {this.props.children}
                <button onClick={this.navigate.bind(this)}>feature</button>
            </div>
        )
    }
}
Layout.contextTypes = {
    router: PropTypes.object.isRequired
}