Ankur Soni Ankur Soni - 6 months ago 51
Javascript Question

Substitute for {...this.state} in React 15.1.0, Pass entire state from parent to child

I am using React 15.1.0.

Suppose there is Parent "P" Component, and it contains a child component "C".

In older versions of react, when I want to pass the entire state to child we used {...this.state} and then we used {this.props.something} from child component.

Is there a simple way in latest Latest React 15.1.0 for above Instance?

Note: I need to pass entire state and not individual props.

<div>
{React.cloneElement(this.props.children, { title: this.state.title })}
</div>


What I am expecting is something like below;

<div>
{React.cloneElement(this.props.children, {...this.state})}
</div>


In Parent component I have below code;

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


In Child Component I am experimenting using below code.

var Speaker = React.createClass({
render() {
return (
<h1>Speaker: {this.state.title}</h1>
);
}
});


But in Chrome Browser, I get below result;

enter image description here

Answer
{...this.state}

equals

this.state

in this case. Spread operator in ES6 (not React-specific feature) ... expands one objects' properties into the parent object, see:

let sampleObject = {
  name: 'a_name'
};

console.log('Non-spread', sampleObject);  // Non-spread {name: "a_name"}
console.log('Spread', {... sampleObject});  // Spread {name: "a_name"}