Using specific APIs inside React.render() should be avoided

  • REACT_MISUSED_API_IN_RENDER
  • Error
  • Medium
  • react

This rule applies when specific APIs are used inside React.render().

The below APIs cannot be used inside React.render() because it triggers nested component updates or accesses unmounted components:

  1. ReactDOM.render()
  2. ReactDOM.unmountComponentAtNode()
  3. ReactDOM.findDOMNode()

In the above cases, React outputs a warning message. Therefore, these APIs should be called inside componentDidUpdate() or componentDidMount() instead of React.render().

For your reference, using setstate() inside React.render() also triggers the nested component updates. This case is detected by REACT_BAD_UPDATE_STATE rule.

Noncompliant Code Example

import React from 'react';
import ReactDOM from 'react-dom';
var createReactClass = require('create-react-class');

var MyComponent = createReactClass({
    render: function () {
        ReactDOM.findDOMNode(this.node).focus(); // REACT_MISUSED_API_IN_RENDER alarm because the component is not mounted yet.
        return (
            <div>
                <input type="text" ref={(node) => this.node = node} />
            </div>
        );
    }
});

ReactDOM.render(<MyComponent />, document.getElementById("root"));

Compliant Code Example

import React from 'react';
import ReactDOM from 'react-dom';
var createReactClass = require('create-react-class');

var MyComponent = createReactClass({
    componentDidMount: function () {
        ReactDOM.findDOMNode(this.node).focus();
    },
    render: function () {
        return (
            <div>
                <input type="text" ref={(node) => this.node = node} />
            </div>
        );
    }
});

ReactDOM.render(<MyComponent />, document.getElementById("root"));

Version

This rule was introduced in DeepScan 1.6.0-beta.

See

  • ReactDOM APIs

  • React Warning: A component is accessing findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.