All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.javascript.rules.javascript.S6788.html Maven / Gradle / Ivy

There is a newer version: 5.0.0.6962
Show newest version

Why is this an issue?

In React, findDOMNode is used to get the browser DOM node given a component instance. However, using findDOMNode is fragile because the connection between the JSX node and the code manipulating the corresponding DOM node is not explicit. For example, changing the external structure of returned JSX will affect the return value of findDOMNode. There are also other caveats when using findDOMNode.

import { Component } from 'react';
import { findDOMNode } from 'react-dom';

class AutoselectingInput extends Component {
  componentDidMount() {
    const input = findDOMNode(this); // Noncompliant: findDOMNode is deprecated
    input.select();
  }

  render() {
    return <input defaultValue="Hello" />
  }
}

Instead, one should get the component’s own DOM node from a ref. Pass your ref as the ref attribute to the JSX tag for which you want to get the DOM node. This tells React to put this <input>’s DOM node into inputRef.current.

Use createRef to manage a specific DOM node. In modern React without class components, the equivalent code would call useRef instead.

import { createRef, Component } from 'react';

class AutoselectingInput extends Component {
  inputRef = createRef(null);

  componentDidMount() {
    const input = this.inputRef.current; // Always points to the input element
    input.select();
  }

  render() {
    return (
      <input ref={this.inputRef} defaultValue="Hello" />
    );
  }
}

Resources

Documentation





© 2015 - 2025 Weber Informatics LLC | Privacy Policy