React API should be called with arguments of correct types

  • REACT_MISMATCHED_TYPE_OF_ARG
  • Error
  • High, Medium
  • react

This rule applies when React API is called with arguments of wrong types.

Because React API has the specification for its arguments, React will throw an error or output a warning message if the types of arguments are wrong.

For example, if setState() is called with null or undefined as the first argument, it is likely a programmer's mistake because neither state update nor re-rendering happens. If unconditional re-rendering was intended, foreceUpdate() should be used instead.

Note: Prior to React 16, if setState() is called with null or undefined as the first argument, re-rendering was triggered.

Noncompliant Code Example

// Example 1
import React from 'react';

class Hello extends React.Component {
    constructor(props) {
        super(props);
        this.state = { greetName: 'hi' };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState('bye'); // REACT_MISMATCHED_TYPE_OF_ARG alarm because the first argument's type of 'setState()' method should be object, function, or null.
    }
    render() {
        return <div onClick={this.handleClick}>{this.state.greetName}</div>;
    }
}

// Example 2
import React from 'react';
import ReactDOM from 'react-dom';

class Hello extends React.Component {
    render() {
        return <div>{this.props.greetName}</div>;
    }
}

ReactDOM.render(
    [<Hello key={'hi'} greetName={'hi'} />, <Hello key={'bye'} greetName={'bye'} />], // REACT_MISMATCHED_TYPE_OF_ARG alarm because the first argument's type of 'ReactDOM.render()' method should be a React component element instead of an array.
    document.getElementById('root'));

Compliant Code Example

// Example 1
import React from 'react';

class Hello extends React.Component {
    constructor(props) {
        super(props);
        this.state = { greetName: 'hi' };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({ greetName: 'bye' });
    }
    render() {
        return <div onClick={this.handleClick}>{this.state.greetName}</div>;
    }
}

// Example 2
import React from 'react';
import ReactDOM from 'react-dom';

class Hello extends React.Component {
    render() {
        return <div>{this.props.greetName}</div>;
    }
}

class HellosWrapper extends React.Component {
    render() {
        return (
            <div>{this.props.hellos.map((prop) => <Hello key={prop} greetName={prop} />)}</div>
        );
    }
}

ReactDOM.render(
    <HellosWrapper hellos={['hi', 'bye']} />,
    document.getElementById('root'));

Version

This rule was introduced in DeepScan 1.5.0-beta.

See

  • CWE-628

  • React Top-Level API

  • React Error: setState(…): takes an object of state variables to update or a function which returns an object of state variables.

  • React Error: ReactDOM.render(): Invalid component element.