ref prop should not be used on React function components

  • REACT_FUNC_COMPONENT_INVALID_REF_PROP
  • Error
  • Medium
  • react

This rule applies when a ref prop is specified on a React function component.

The ref prop is used to provide a reference to the component instance of the current element. However, because a function component does not have any instances, it cannot be used on an element corresponding to a function component.

If the intention is to refer an inner element of the function component, you can use React.forwardRef() instead.

Noncompliant Code Example

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

function MyInput(props) {
    return <input />;
}
class App extends React.Component {
    constructor(props) {
        super(props);
        this.myInput = React.createRef();
    }
    render() {
        return <MyInput ref={this.myInput}/>; // REACT_FUNC_COMPONENT_INVALID_REF_PROP alarm
    }
}

Compliant Code Example

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

const MyInput = React.forwardRef((props, ref) => {
    return <input ref={ref}/>;
}
class App extends React.Component {
    constructor(props) {
        super(props);
        this.myInput = React.createRef();
    }
    render() {
        return <MyInput ref={this.myInput}/>;
    }
}

Version

This rule was introduced in DeepScan 1.27.0.

See

  • React Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

  • Refs and Function Components