React forwardRef

In React, forward refs provide a way for parent components to access and interact with a child component’s DOM nodes or refs. This is especially useful when you need to manipulate a child component’s elements, like focusing an input field or adjusting its styles, from the parent component.

Why Use Forward Refs?

Normally, refs are only available in the component where they are created. However, by using React.forwardRef, you can pass the ref from the parent to the child, giving the parent control over the child’s DOM elements.

Example of Forward Refs:

import React, { useRef } from 'react';

// Child component accepting forwarded ref
const CustomInput = React.forwardRef((props, ref) => (
  <input ref={ref} {...props} />
));

function ParentComponent() {
  const inputRef = useRef(null);

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

  return (
    <div>
      <CustomInput ref={inputRef} placeholder="Click the button to focus me" />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}

export default ParentComponent;

How It Works:

  1. The CustomInput component uses React.forwardRef to accept a ref prop from its parent.
  2. In the ParentComponent, useRef creates a reference, which is passed down to CustomInput via the ref attribute.
  3. The focusInput function triggers the focus() method on the input element inside the CustomInput component, utilizing the forwarded ref.

Benefits of Forward Refs:

  • Encapsulation: It allows child components to encapsulate logic while giving controlled access to the parent for specific operations like focusing or measuring size.
  • Functional Components: Normally, only class components can handle refs directly. Forward refs allow functional components to receive refs too.

Conclusion:

Forward refs are an excellent tool when you need to build reusable components that can be manipulated from parent components. They bridge the gap between component encapsulation and direct DOM access, making it easier to handle specific UI operations.


Read More