glowkeeper glowkeeper - 1 month ago 11
React JSX Question

What's the proper way to pass dependencies between comnponents in react?

Imagine that Component A creates a list of items that Component B needs to display. What's the proper way to pass data from Component A to Component B from their parent?

For example, let's say that Component A's constructor creates a list of items and has a function

_getListItems()
that returns that list. I'm hoping the parent can then pass that list on to other components via props.

My naive (non-working) implementation has their parent attempting to render the components like this:


render () {
return (
<div>
<h1>Data Test</h1>

<ComponentA ref='compa'/>
<ComponentB items={this.refs.compa._getListItems()}/>
</div>
);
}


....although the code above doesn't work, I hope it illustrates what I'm trying to do.

ps. nOOb to react and javascript, so forgive me if the answer to my question's obvious...

Answer

Divide your components into two separate categories.

  • Presentational Component that has responsibility to display a thing. This component should not have state (except for UI state).
  • Container Component that knows the data.

https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.skmxo7vt4

So, in your case the data should created by parent of ComponentA and ComponentB and pass the data to both ComponentA and ComponentB via props.

Example:

render(){
    let items = this._getListItems();
    return (
        <div>
            <ComponentA items={items} />
            <ComponentB items={items} />
        </div>
    );
}

Edit

Rewrite OP's approach in the comment:

class MyContainer extends React.Component { 
    constructor(props) { 
        super(props);
        this.state = { stuff: [1,2,3] }; 
    } 

    render() { 
        return ( 
            <div>
                <ComponentA items={this.state.stuff} /> 
                <ComponentB items={this.state.stuff} /> 
            </div> 
        ); 
    } 
}
Comments