contextType property of a React component should be specified properly

  • REACT_BAD_CONTEXT_TYPE
  • Error
  • Medium
  • react

This rule applies when the static contextType property of a React component is not properly specified.

The contextType property is used to consume a context created with React.createContext(). When the property is specified for a React component, you can access the current value of the context using this.context inside lifecycle methods of the component.

This rule checks the following improper usages of contexts:

  1. Values other than the context objects returned by React.createContext() are assigned to the contextType property. Note that you should use the context object itself, not the Consumer or Provider property of the context object.
  2. Context objects are assigned to the legacy contextTypes property instead of the contextType.

In the above cases, React outputs warning messages and wrong values may be accessed at this.context.

Noncompliant Code Example

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

let MyContext = React.createContext("there");

export class Example1 extends React.Component {
    static contextType = MyContext.Consumer; // REACT_BAD_CONTEXT_TYPE alarm because consumer is assigned instead of context object.
    render() {
        return <div>Hello {this.context}</div>;
    }
}

export class Example2 extends React.Component {
    static contextTypes = MyContext; // REACT_BAD_CONTEXT_TYPE alarm because context object is assigned to 'contextTypes' instead of 'contextType'.
    render() {
        return <div>Hi {this.context}</div>;
    }
}

Compliant Code Example

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

let MyContext = React.createContext("there");

export class Example1 extends React.Component {
    static contextType = MyContext;
    render() {
        return <div>Hello {this.context}</div>;
    }
}

export class Example2 extends React.Component {
    static contextType = MyContext;
    render() {
        return <div>Hi {this.context}</div>;
    }
}

Version

This rule was introduced in DeepScan 1.33.0.

See

  • Class.contextType

  • React Warning: SayHello defines an invalid contextType. contextType should point to the Context object returned by React.createContext(). Did you accidentally pass the Context.Consumer instead?

  • React Warning: Failed context type: SayHi: context type $$typeof is invalid; it must be a function, usually from the prop-types package, but received symbol.

Was this documentation helpful?