The child node of a React context consumer should be specified properly

  • REACT_BAD_CONTEXT_CONSUMER_CHILD
  • Error
  • High
  • react

This rule applies when the child node of a React context consumer is not specified properly.

The child node of a context consumer should be a function that takes the current context value and returns a React node to render.

If an incorrect value is passed or multiple children are specified, React outputs a warning message and a TypeError exception is thrown.

Noncompliant Code Example

View with compliant examples side by side
import React from 'react';

export let Context = React.createContext('foo');

export function Example1() {
    return (
        // REACT_BAD_CONTEXT_CONSUMER_CHILD alarm because the function is not directly specified as a child. (TypeError: render is not a function)
        <Context.Consumer>
            <div>
                { value => <div className={value}>Example 1</div> }
            </div>
        </Context.Consumer>
    );
}

export function Example2() {
    return (
        // REACT_BAD_CONTEXT_CONSUMER_CHILD alarm because leading and trailing whitespaces around the JSX expression result in text nodes.
        <Context.Consumer> { value => <div className={value}>Example 2</div> } </Context.Consumer>
    );
}

Compliant Code Example

View with noncompliant examples side by side
import React from 'react';

export let Context = React.createContext('foo');

export function Example1() {
    return (
        <Context.Consumer>
            { value => <div className={value}>Example 1</div> }
        </Context.Consumer>
    );
}

export function Example2() {
    return (
        <Context.Consumer>{ value => <div className={value}>Example 2</div> }</Context.Consumer>
    );
}

Version

This rule was introduced in DeepScan 1.38.0.

See

  • Context.Consumer

  • Children in JSX

  • React Warning: A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it.

Was this documentation helpful?