Skip to content

Instantly share code, notes, and snippets.

@tmbtech
Created June 24, 2015 22:20
Show Gist options
  • Save tmbtech/43b108c55292a6864d10 to your computer and use it in GitHub Desktop.
Save tmbtech/43b108c55292a6864d10 to your computer and use it in GitHub Desktop.
react router v1 context not working?
var React = require('react');
import HashHistory from 'react-router/lib/HashHistory';
var { Router, Route, Link, Navigation } = require('react-router');
var App = React.createClass({
childContextTypes: {
foo: React.PropTypes.object.isRequired
},
getChildContext() {
return {
foo: {bar:"value"}
};
},
mixins: [ Navigation ],
getInitialState: function () {
return {
tacos: [
{ name: 'duck confit' },
{ name: 'carne asada' },
{ name: 'shrimp' }
]
};
},
addTaco: function () {
var name = prompt('taco name?');
this.setState({
tacos: this.state.tacos.concat({name: name})
});
},
handleRemoveTaco: function (removedTaco) {
var tacos = this.state.tacos.filter(function (taco) {
return taco.name != removedTaco;
});
this.setState({tacos: tacos});
this.transitionTo('/');
},
render: function () {
var links = this.state.tacos.map(function (taco, i) {
return (
<li key={i}>
<Link to={`/taco/${taco.name}`}>{taco.name}</Link>
</li>
);
});
return (
<div className="App">
<button onClick={this.addTaco}>Add Taco</button>
<ul className="Master">
{links}
</ul>
<div className="Detail">
{this.props.children && React.cloneElement(this.props.children, {
onRemoveTaco: this.handleRemoveTaco
})}
</div>
</div>
);
}
});
var Taco = React.createClass({
contextTypes: {
router: React.PropTypes.object,
foo: React.PropTypes.object
},
remove: function () {
this.props.onRemoveTaco(this.props.params.name);
},
render: function () {
console.log(this.context.foo); // this doesn't work.
return (
<div className="Taco">
<h1>{this.props.params.name}</h1>
<button onClick={this.remove}>remove</button>
</div>
);
}
});
React.render((
<Router history={new HashHistory}>
<Route path="/" component={App}>
<Route path="taco/:name" component={Taco}/>
</Route>
</Router>
), document.getElementById('example'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment