ref
prop should not be used on React function components
This rule applies when aref
prop is specified on a React function component.
Theref
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 useReact.forwardRef()
instead.
Note: The application of this rule is limited to projects using React 18 or below because React 19 supports usingref
for function components.
Noncompliant Code Example | Compliant Code Example | ||
---|---|---|---|
1 | import React from 'react'; | 1 | import React from 'react'; |
2 | 2 | ||
3 | function MyInput(props) { | 3 | const MyInput = React.forwardRef((props, ref) => { |
4 | return <input />; | 4 | return <input ref={ref}/>; |
5 | } | 5 | }); |
6 | 6 | ||
7 | export class App extends React.Component { | 7 | export class App extends React.Component { |
8 | constructor(props) { | 8 | constructor(props) { |
9 | super(props); | 9 | super(props); |
10 | this.myInput = React.createRef(); | 10 | this.myInput = React.createRef(); |
11 | } | 11 | } |
12 | render() { | 12 | render() { |
13 | return <MyInput ref={this.myInput}/>; // REACT_FUNC_COMPONENT_INVALID_REF_PROP alarm | 13 | return <MyInput ref={this.myInput}/>; |
14 | } | 14 | } |
15 | } | 15 | } |
import React from 'react';function MyInput(props) { return <input />;}export 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 }}
import React from 'react';const MyInput = React.forwardRef((props, ref) => { return <input ref={ref}/>;});export class App extends React.Component { constructor(props) { super(props); this.myInput = React.createRef(); } render() { return <MyInput ref={this.myInput}/>; }}
This rule was introduced in DeepScan 1.27.0.
React Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?