What Is React Forward Ref? Complete Example Tutorial Guide

What Is React Forward Ref?

React forwardRef allows you to pass a ref from a parent component to a child component.
It’s useful when you need direct access to DOM elements in child components.


Basic Syntax

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref}>{props.children}</button>
));

Example

import React, { useRef } from "react";

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

function App() {
  const inputRef = useRef();

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

  return (
    <div>
      <Input ref={inputRef} />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}

export default App;

✅ The parent component can focus the input inside the child component using ref.


Key Points

  • Enables parent-to-child ref passing
  • Works with functional components
  • Use useRef in parent to access child’s DOM
  • Useful for modals, inputs, or custom UI elements

Conclusion

React Forward Ref allows clean access to child DOM elements, making component interactions more flexible and reusable.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *