JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Function components cannot have string references in React

Author:JIYIK Last Updated:2025/03/17 Views:

When we use a string as a reference in a function component, we get an error “ Function components cannot have string refs ”. To fix the error, use useRef()the hook to get a mutable ref object that we can use as a ref inside the component.

Here is the sample code that produces the above error

export default function App() {
  // A string ref has been found within a strict mode tree.
  // ⛔️ Function components cannot have string refs.
  // We recommend using useRef() instead.
  return (
    <div>
      <input type="text" id="message" ref="msg" />
    </div>
  );
}

Function components cannot have string references in React

The problem in your code snippet is that we use strings as references.

To work around the error, use useRefthe hook to obtain a mutable reference object instead.

import {useEffect, useRef} from 'react';

export default function App() {
  const refContainer = useRef(null);

  useEffect(() => {
    // 👇️ this is reference to input element
    console.log(refContainer.current);

    refContainer.current.focus();
  }, []);

  return (
    <div>
      <input type="text" id="message" ref={refContainer} />
    </div>
  );
}

useRef()The hook can be passed an initial value as an argument. The hook returns a mutable ref object whose .current property is initialized to the passed argument.

请注意, we have to access the current property of the ref object in order to access the input element on which we set the ref attribute.

When we pass the ref prop to an element, like, React sets the .current property of the ref object to the corresponding DOM node.

useRefThe hook creates a normal JavaScript object but gives you the same ref object on every render. In other words, it's almost a .currentmemoized object value with a property.

It is important to note that when you change the value of the ref's current attribute, it will not cause a re-render.

For example, ref does not have to be included useEffectin the dependencies array of the hook, since changing its current properties will not cause a re-render.

import {useEffect, useRef} from 'react';

export default function App() {
  const refContainer = useRef(null);

  const refCounter = useRef(0);

  useEffect(() => {
    // 👇️ this is reference to input element
    console.log(refContainer.current);
    refContainer.current.focus();

    // 👇️ incrementing ref value does not cause re-render
    refCounter.current += 1;
    console.log(refCounter.current);
  }, []);


  return (
    <div>
      <input type="text" id="message" ref={refContainer} />
    </div>
  );
}

The hook in the example useEffectis only run twice because useRefdoes not notify us when its content changes.

Changing the current properties of an object will not cause a re-render.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Joining columns using Select in PostgreSQL

Publish Date:2025/04/11 Views:176 Category:PostgreSQL

MySQL PostgreSQL is an object-relational database system, which means it can support more complex data types than its competitors . Today we will learn how to use SELECT the operator to join the columns of a table. Using operators to || joi

Splitting a string into variables in Bash

Publish Date:2025/03/23 Views:58 Category:OPERATING SYSTEM

This article will discuss different ways to split a string into variables in Bash. We will start our discussion with a brief introduction to strings. Later, we will discuss various ways to split a string using Bash examples. Strings in Bash

Bash remove newline from string

Publish Date:2025/03/23 Views:184 Category:OPERATING SYSTEM

This article explains how to remove newlines from a string in Bash. Creating a string with newlines in Bash Sometimes, it is required that a string does not have newline characters in it. Bash provides several methods to remove newline char

Remove the first character from a string in Bash

Publish Date:2025/03/23 Views:61 Category:OPERATING SYSTEM

Removing the first character of a string can be tricky in Bash because there is no built-in function that can do this directly. However, there are several ways to achieve this, such as using the sed command, the cut command, or substring pa

Replace characters in a string using Bash

Publish Date:2025/03/23 Views:84 Category:OPERATING SYSTEM

A common operation involving string literals is replacing individual characters or substrings within the string with other characters or substrings. In this article, we will look at several ways to do string replacement using the BASH shell

String comparison operators in Bash

Publish Date:2025/03/23 Views:99 Category:OPERATING SYSTEM

In this article, we will explain string comparison in Bash using if statement. The shell program that runs in Linux and provides a command line interface for users to execute different commands is called Bash shell. It is also used as the d

Convert a string to an integer in Bash

Publish Date:2025/03/23 Views:154 Category:OPERATING SYSTEM

This article will discuss string to integer conversion in Bash script. First, we will discuss the math operations on strings and then we will see how to convert a string to an integer. Mathematical operations on strings Let's start our disc

Get the length of a string in Bash

Publish Date:2025/03/23 Views:145 Category:OPERATING SYSTEM

In programming languages, the length or size of a data type plays an important role. It helps in list traversal and facilitates the extraction of useful information. The length is especially important when performing tasks that require trav

How to avoid cross-origin (CORS) issues in React/Next.js

Publish Date:2025/03/17 Views:170 Category:NETWORK

In this article, we will introduce how to avoid cross-origin (CORS) issues in React/Next.js. Cross-origin resource sharing (CORS) is a protocol that defines how web requests should be handled when crossing different URLs.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial