Full Stack Development

forwardRef

by Tomas Trescak t.trescak@westernsydney.edu.au

forwardRef

React 18

      import React, { forwardRef, useRef, render } from "react";

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

const Parent = () => {
  const inputRef = useRef();

  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <h1>Using forwardRef with React 18</h1>
      <Input 
        ref={inputRef} 
        placeholder="Type something..." 
      />
      <button onClick={focusInput}>
        Focus the Input
      </button>
    </div>
  );
};

render(<Parent />)

    

forwardRef

React 19

      import React, { forwardRef, useRef, render } from "react";

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

const Parent = () => {
  const inputRef = useRef();

  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <h1>Using forwardRef with React 19</h1>
      <Input 
        ref={inputRef} 
        placeholder="Type something..." 
      />
      <button onClick={focusInput}>
        Focus the Input
      </button>
    </div>
  );
};

render(<Parent />)

    

forwardRef

Key Takeways

  • Use ref directly for DOM elements where possible.
  • Use forwardRef when building custom components
  • React 19 simplifies the API without forwardRef