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;
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With