Ankur Soni
Ankur Soni

Reputation: 6018

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 wanted 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

Upvotes: 3

Views: 1770

Answers (2)

Ankur Soni
Ankur Soni

Reputation: 6018

I just changed the below code snippet,

Speaker: {this.props.title}

in child component and voila!!! the code worked. Thank you all guys.

Below is the snapshot. enter image description here

Upvotes: 0

Maciek Jurczyk
Maciek Jurczyk

Reputation: 575

{...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"}

Upvotes: 2

Related Questions