Can we pass the entire state object to the child component?

Question

In the context of this exercise, can we pass the entire state object to the child component?

Answer

Yes, you can do this by using the spread operator in JavaScript, which is done like the following, by adding three dots in front of the object {...this.state}.

// Given this state for a component.
this.state = {
  key1: 'val1',
  key2: 'val2'
}

// We can pass the entire state object to a child component as follows.
// Keep in mind that we do not set any attribute to it.
<Child {...this.state} />

// This is equivalent to doing the following.
<Child key1={this.state.key1} key2={this.state.key2} />
11 Likes

Hello,

That’s an interesting way to pass the entire state object to the Child. I know using spread operators, you can use a loop to retrieve the values, but will that be in props? I mean I not sure how to extract these state values in the Child Component.

import React from ‘react’;

export class Child extends React.Component{
render(){
return(
??? // Guessing it will be coming in as props - but not sure how to traverse
);
}
}

2 Likes

Hi,

If you pass the state as props using {…this.state} in parent component, you can use it in child component as {this.props.“key name of parent state object”}. For example:

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            header: 'hello',
            footer: 'bye',
            body: 'howdy'
        }
    }

    render() {
        return <Child {...this.state} />
    }
}

class Child extends React.Component {
    render() {
        return (
            <div>
                <h1>{this.props.header</h1>
                <p>{this.props.body}</p>
                <footer>{this.props.body}</footer>
            </div>
        )
    }
}

Is this in any way slower/less efficient than passing individual variables/functions?