Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error 'Function components cannot have string refs' in react to do app

Tags:

reactjs

I followed a simple to do react tutorial on YouTube I built the same app 10 times
But i'm getting this error:
'Error: Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref'

I'm already using useRef and JSlint doesn't mention errors. What am I doing wrong?

import { useEffect, useRef, useState } from 'react';
import './App.css';

function App() {
  //state
  const [todos, setTodos] = useState([]);
  const todoTextRef = useRef(null);

  useEffect(() => {
    const existingTodos = localStorage.getItem('todos');
    setTodos(existingTodos ? JSON.parse(existingTodos) : []);
  },[]);

  function addToDo(event) {
    event.preventDefault();
    const next = [...todos, todoTextRef.current.value];
    localStorage.setItem('todos',JSON.stringify(next));
  }

  return (
    <div>
      <ul>
        {todos.map(todo => (<li key={todo}>{todo}</li>))}
      </ul>

      <form onSubmit={addToDo}>
        <input ref="{todoTextRef}" type="text"/>
        <input type="submit" value="Add to do" />
      </form>
    </div>
  );
}

export default App;
like image 739
Oba Api Avatar asked Mar 24 '26 20:03

Oba Api


2 Answers

You can also see this error is you inadvertently use Typescript syntax for useRef in a Javascript app.

If so, you need to replace, for example:

const yourRef useRef<HTMLDivElement>(null)

with:

const yourRef useRef(null)
like image 158
Mick Avatar answered Mar 26 '26 09:03

Mick


Because you're using quotes, it's causing the interpreter to read this as a string ref. If you remove the quotes, it will then interpret it as a variable. Use this syntax:

<input ref={todoTextRef} type="text"/>

as opposed to:

<input ref="{todoTextRef}" type="text"/> // React will see this as a string input to the ref property.
like image 22
silencedogood Avatar answered Mar 26 '26 08:03

silencedogood