ragmha
ragmha

Reputation: 631

Passing state to child components as properties

I am currently learning React router v1.0 and I'm having a confusion with passing state to child components as properties.

App.js

  getInitialState: function(){
  return {
    status: 'disconnected',
    title: ''
  },
  ...
  ,
  render: function(){
    return (
      <div>
        <Header title={this.state.title} status={this.state.status}/>
        {React.cloneElement(this.props.children,{title:this.state.title,status:this.state.status})}
      </div>
    );

Client.js

var routes = (
  <Router history={hashHistory}>
  <Route path="/" component={App}>
    <IndexRoute component={Audience} />
    <Route path ="speaker" component={Speaker} />
  </Route>
</Router>
);

Audience.js

render: function(){
  return(
  <div>
    <h1>Audience</h1>
    {this.props.title || "Welcome Audience"}
    </div>
 );
}

Speaker.js

render: function(){
    return(
    <div>
     <h1>Speaker:</h1>
     {this.props.status || "Welcome Speaker!"}
    </div>
  );
  }

Instead of doing this:

{React.cloneElement(this.props.children,{title:this.state.title,status:this.state.status})}

Is there something similar like this for React.cloneElement using the https://facebook.github.io/react/docs/jsx-spread.html operator:

<RouteHandler {...this.state}/>

TLDR; Basically I would like to pass the entire state to my Route Components instead of individually defining them.

Any help would be greatly appreciated!

Upvotes: 4

Views: 1960

Answers (1)

Andr&#233; Junges
Andr&#233; Junges

Reputation: 5347

Well, the simple answer would be just no.


As you can see in this comment - there are some ways to achieve this behaviour (the way you're doing is one of them), and maybe you've seen all of them already, but I wouldn't suggest you to use any of them, unless really necessary.

You should really check these discussions about it in the following threads:

https://github.com/reactjs/react-router/issues/1857

https://github.com/reactjs/react-router/issues/1531

@ryanflorence [Co-author of React-router]

You should think of your route components as entry points into the app that don't know or care about the parent, and the parent shouldn't know/care about the children.

Usually the best way to handle these cases would be using something like redux - where the whole state of your app is stored in an object tree and it can be easily shared across your route components.

Upvotes: 1

Related Questions