← React Beginner Questions - Set 6 Q57

What is the purpose of React.forwardRef?

React Beginner Questions - Set 6

A ref is not a prop: it never reaches a function component's props. `forwardRef` is how a ref is handed through to a DOM node inside.

Example

import { forwardRef, useRef } from 'react';

const TextInput = forwardRef(function TextInput(props, ref) {
  return <input ref={ref} {...props} />;
});

export default function Form() {
  const emailRef = useRef(null);

  return (
    <form onSubmit={e => { e.preventDefault(); emailRef.current.focus(); }}>
      <TextInput ref={emailRef} placeholder="email" />
      <button type="submit">Focus the field</button>
    </form>
  );
}

What to notice

← Back to the question list