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 sideimport { createContext } from 'react';
export const MyContext = createContext('foo');
export function Example1() {
return (
// REACT_BAD_CONTEXT_CONSUMER_CHILD alarm because the function is not directly specified as a child.
<MyContext.Consumer>
<div>
{ value => <div className={value}>Example 1</div> }
</div>
</MyContext.Consumer>
);
}
export function Example2() {
return (
// REACT_BAD_CONTEXT_CONSUMER_CHILD alarm because leading and trailing whitespaces around the JSX expression result in text nodes.
<MyContext.Consumer> { value => <div className={value}>Example 2</div> } </MyContext.Consumer>
);
}
Compliant Code Example
View with noncompliant examples side by sideimport { createContext } from 'react';
export const MyContext = createContext('foo');
export function Example1() {
return (
<MyContext.Consumer>
{ value => <div className={value}>Example 1</div> }
</MyContext.Consumer>
);
}
export function Example2() {
return (
<MyContext.Consumer>{ value => <div className={value}>Example 2</div> }</MyContext.Consumer>
);
}
Version
This rule was introduced in DeepScan 1.38.0.
See
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.
Uncaught TypeError: Component is not a function