Reputation: 1127
I have been using React-Router for the past couple of days and Iv'e been loving it! One problem that Iv'e been having is that I can't find the best way to pass state from my parent component to my child component. Iv'e been looking at several stack overflow and blog posts but I can't seem to find what Iv'e wanted. Here is a very over simplified example about what I'm looking for.
class App extends React.Component {
constuctor(props) {
super(props);
this.state = {name:"helloworld", lastname:"world hello"};
}
render() { // SOMETHING LIKE THIS WOULD BE PREFFERED
if (this.props.children.name == "Home") {
{this.props.children myname={this.state.name}}
}
else if (this.props.children.name = "Account") {
{this.props.children anotherprop={this.state.lastname}}
}
}
}
class Home extends React.Component {
render() {
return (
{this.props.myname}
);
}
}
class Account extends React.Component {
render() {
return (
{this.props.lastname}
);
}
}
//ROuting config - (Only the routes not the config)
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="account" component={account} />
</Route>
Obviously this is a very simplified version of what I am trying to accomplish but I hope you get the picture.
TLDR: How do I pass state from parent to child as props? Is there any way to do this via the parent component?
Any help would be greatly appreciated!
Upvotes: 10
Views: 7292
Reputation: 546
lufte - if your original code looked like this:
render() {
return(
<div className="wrapper">
{this.props.children}
</div>
);
}
then the revised code with data being passed to the component's children would be:
render() {
var clonedChildren = React.cloneElement(this.props.children, {myProp: myValue});
return(
<div className="wrapper">
{clonedChildren}
</div>
);
}
Upvotes: 1
Reputation: 1127
All I did to fix this was use the cloneElement to create a clone and I could add my state props to that clone:
return React.cloneElement(
this.props.children,
{appName: 'Foo'}
);
}
Upvotes: 5
Reputation: 146
You can use context to pass data from parent to child component. Please refer example at https://facebook.github.io/react/docs/context.html
This perfectly works even if you use react-router, i am using it in my application.
Upvotes: 2