Search code examples
javascriptreactjschildrendescendant

React pass props down to all descendant Components


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


Solution

  • 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
    };