React newbie here. I found out this is not the correct way to pass useRef() to child components but why is it not throwing an error and seems to be working fine.
const App = () => {
const todoRef = useRef(null);
const [todos, setTodos] = useState([]);
const onFormSubmit = (e) => {
e.preventDefault();
const todo = todoRef.current.value;
if (todo.trim().length > 0) {
setTodos((prevTodo) => [
...prevTodo,
{ title: todo, isCompleted: false },
]);
todoRef.current.value = null;
}
};
return (
<div>
<h1>Todos</h1>
<InputField onFormSubmit={onFormSubmit} todoRef={todoRef} />
<TodoList todos={todos} />
</div>
);
};
const InputField = ({ onFormSubmit, todoRef }) => {
return (
<form onSubmit={onFormSubmit}>
<input
type="text"
name="task"
placeholder="What task needs to be completed?"
ref={todoRef}
/>
</form>
);
};
I didn’t find anything related to this specific question.
2
Answers
You need to wrap the child component in a forwarRef call as in:
You can read more here: https://react.dev/reference/react/forwardRef
In addition to using forwardRef, it’s worth mentioning that the way you are doing it now is perfectly valid.
If your component has multiple refs, forwardRef can only forward one of them. The rest will need to be passed the way you are doing now.