skip to Main Content

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


  1. You need to wrap the child component in a forwarRef call as in:

    import { forwardRef } from 'react';
    
    const MyInput = forwardRef(function MyInput(props, ref) {
      const { label, ...otherProps } = props;
      return (
        <label>
          {label}
          <input {...otherProps} ref={ref} />
        </label>
      );
    });
    

    You can read more here: https://react.dev/reference/react/forwardRef

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search