Movatterモバイル変換


[0]ホーム

URL:


ref prop should not be used on React function components

  • REACT_FUNC_COMPONENT_INVALID_REF_PROP
  • Error
  • Medium
  • react

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 ExampleCompliant Code Example
1import React from 'react';1import React from 'react';
22
3function MyInput(props) {3const MyInput = React.forwardRef((props, ref) => {
4 return <input />;4 return <input ref={ref}/>;
5}5});
66
7export class App extends React.Component {7export 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 alarm13 return <MyInput ref={this.myInput}/>;
14 }14 }
15}15}

Noncompliant Code Example

View with compliant examples side by side
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  }}

Compliant Code Example

View with noncompliant examples side by side
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}/>;  }}

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

Was this documentation helpful?

Last updated on April 29, 2025

[8]ページ先頭

©2009-2025 Movatter.jp