1

Consider this

Parent component (prop: textColor)
intermediate component 1
intermediate component 2
intermediate component N
Component with text (needs textColor)

How do I go about avoiding passing textColor through intermediate components explicitly?

Is this a good use case for Context even though it has warnings that discourage its usage for different reasons?

ave
  • 18,083
  • 9
  • 30
  • 39
  • if you are using redux then store textColor in ```Store``` get from store into your any Component as ```props```. – kartikag01 Jan 09 '17 at 17:23
  • @Kartik_Agarwal that's right, but it means those components that can access `store` as a prop are containers, not representational (aka simple) components. That's why I'm hesitating to do it, I think those components that are very deep down the tree should be simple. – ave Jan 09 '17 at 17:59

2 Answers2

1

If textColor doesn't change / is not part of state, you can define it as a variable and import it on demand.

Otherwise, you should use context as this is exactly its use case.

In some cases, you want to pass data through the component tree without having to pass the props down manually at every level

Lyubomir
  • 19,615
  • 6
  • 55
  • 69
1

As leo suggested it, use context:

class ParentComponent extends React.Component {
    static childContextTypes = {
        someContext: React.PropTypes.string
    };

    getChildContext() {
        return {
            someContext: 'foo-bar'
        };
    }

}

Then the Nth child component does:

class NthChild extends React.Component {
    static contextTypes = {
        someContenxt: React.PropTypes.string
    };

    render() {
        // this.context.someContext is available here
    }
}
Kousha
  • 32,871
  • 51
  • 172
  • 296
  • Is this still the best answer? The [react documentation](https://facebook.github.io/react/docs/context.html) seems to strongly discourage the use of context. – randomsolutions Jul 16 '17 at 16:13
  • @randomsolutions I actually have to disagree. `context` is an advanced feature and if you know what you are doing, then it is fine. The biggest problem is that it is an experimental API, so it will most likely changes. Redux Connect function uses context. See https://stackoverflow.com/questions/36428355/react-with-redux-what-about-the-context-issue – Kousha Jul 17 '17 at 17:30