Reputation: 3545
I have a route model made up in react-router. I want to know how to pass props between my components in this setup - is it possible?
<Route path='/' component={Layout}>
<IndexRoute component={Home} />
<Route path='/users' component={Users} />
<Route path='/posts' component={Posts} />
<Route path='/albums' component={Albums} />
<Route path='/about' component={About} />
</Route>
Say for example, I initialise my state in the Layout component (the idea being that all it's children can access the state); how would I pass the state value to them, and also trigger functions in the parent component passed down via props?
Is this possible, as it would be if the component were directly nested in it's parent, or am I thinking about this in the wrong way with regards to routing? If so, is there an alternative solution?
Any help appreciated
Upvotes: 1
Views: 1668
Reputation: 6458
Yes it's possible. You can use context in Layout
component. Here's an example in ES6:
export default class Layout extends React.Component {
static childContextTypes = {
layoutState: React.PropTypes.object
}
getChildContext() {
return {layoutState: this.state};
}
}
Then just declare the context in child/grandchild components:
export default class Users extends React.Component {
static contextTypes = {
layoutState: React.PropTypes.object
}
render() {
const {layoutState} = this.context;
// then just use your layoutState and return
}
}
Upvotes: 2