Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing state as props from Parent to Child in React-Router?

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!

like image 935
mre12345 Avatar asked Feb 04 '16 04:02

mre12345


1 Answers

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'}
    );
}
like image 137
mre12345 Avatar answered Oct 20 '22 01:10

mre12345