Tabbyofjudah
Tabbyofjudah

Reputation: 2133

React... setting child Properties from State

I have read that it is an anti-pattern to set state from props, but what about setting child properties from state? Is this code okay, or is there a better practice.

Let's say we have an APP component that holds and changes it's state. Is it good practice to pass that state down to child display components as props?

   var APP = React.createClass({

   getInitialState() {
       return {
           items: [1,2,3],
           title: 'Simple Sample'
       };
   },

   render() {
       return <div>
           <Display title={this.state.title} />
           <List items={this.state.items} />
       </div>
   }
});

What about something like this:

   var APP = React.createClass({

   getInitialState() {
       return {
           items: [1,2,3],
           title: 'Simple Sample'
       };
   },

   render() {
       return <div>
           <DisplayList {...this.state} />
       </div>
   }
});

Upvotes: 0

Views: 181

Answers (1)

Michelle Tilley
Michelle Tilley

Reputation: 159105

Passing a parent's state into a child's props is the primary way of communicating with children. Passing function references to a child's props is the primary way of allowing the child to communicate back to the parent.

I personally avoid the <DisplayList {...this.state} /> pattern because I prefer to be explicit about the DisplayList's API and what props need to be passed. Passing the whole state can lead to subtle bugs when you add another variable later.

The antipattern you mention is probably the pattern of taking a component's props and copying them to that same component's state—it then becomes more difficult to figure out who owns the data, and whether you should call setState or call some method on this.props.

Upvotes: 1

Related Questions