6

The use case is I would like to "effortlessly" pass down a certain prop values to all descendant components. Not sure if this is even possible in React.

So instead of doing this:

class Parent extends Component {
    constructor() {
        super(props);
        this.props.componentID = "123456";
    }
    render() {
        return <Child1 componentID={this.props.componentID} />
    }
}

class Child1 extends Component {

    render() {
        return <Child2 componentID={this.props.componentID} />
    }
}

class Child2 extends Component {

    render() {
        return <div>{this.props.componentID}</div>
    }
}

Do something like this:

class Parent extends Component {
    constructor() {
        this.props.componentID = "123456";
    }

    passComponentIDToAllDescendantComponents() {
        // Some super nifty code
    }

    render() {
        return <Child1 />
    }
}

// etc...

Thanks for the help

1ven
  • 6,776
  • 1
  • 25
  • 39
slim1801
  • 531
  • 3
  • 8
  • 19
  • dont modify the props.. use setState – webdeb Aug 06 '16 at 16:03
  • 4
    You should look at React's Context: https://facebook.github.io/react/docs/context.html – madox2 Aug 06 '16 at 16:03
  • @madox2 Thanks!!! Just what I was looking for – slim1801 Aug 06 '16 at 16:12
  • @madox2, Your comment should be marked as answer. I was about to write that this was not possible till I saw the React documentation. I felt passing props made sure that the code was readable. – vijayst Aug 06 '16 at 16:38
  • Word of caution: make sure that there's a strong reason to pass the props this way down the tree in an invisible fashion (because your component jsx no more tells the full truth). Plus as of this writing, ReactJS docs say that this is an experimental feature, so it could change in the future in a way that can break your app. – KumarM Aug 06 '16 at 17:27
  • Here's a nice summary on when to use and when not to use: http://reactkungfu.com/2016/01/react-context-feature-in-practice/ – KumarM Aug 06 '16 at 17:30

1 Answers1

6

You can use Context feature to pass data down to the children. In your case it could look like this:

class Parent extends Component {
    getChildContext() {
        return {componentID: "123456"};
    }
    render() {
        return <Child1 />
    }
}

Parent.childContextTypes = {
    componentID: React.PropTypes.string
};

class Child1 extends Component {

    render() {
        return <Child2 />
    }
}

class Child2 extends Component {

    render() {
        return <div>{this.context.componentID}</div>
    }
}

Child2.contextTypes = {
    componentID: React.PropTypes.string
};
madox2
  • 49,493
  • 17
  • 99
  • 99