React ForwardRefs: a small tip

Have you ever struggled with React ForwardRefs? It can be a frustrating experience trying to get them to work properly.

React  ForwardRefs: a small tip
Photo by Fernando Reyes / Unsplash

Just ran into a frustrating problem with React  ForwardRefs – turns out it's not so straightforward to pass refs to child components. It can be a frustrating experience trying to get them to work properly.

One common issue is when you try to pass a ref from a parent component to a child component, but the child component doesn't render properly.

Another issue is when you try to use ForwardRefs with higher-order components, but the ref doesn't pass through properly. ForwardRefs can make code harder to read and maintain, as they require a different syntax and approach to traditional React components.

To avoid these issues, ensure you understand how to properly use ForwardRefs and have a solid grasp of the React component lifecycle. React ForwardRefs can be helpful in certain situations. Here's an example of a ForwardRef that focuses an input when it's rendered:

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

ReactDOM.render(
	<FocusInput ref={input => input.focus()} />,
    document.getElementById('root')
);

You can also use ForwardRefs to pass a reference to a parent component, which is useful for cases where you need to measure the size or position of a child element:

const MyComponent = React.forwardRef((props, ref) => {
  return (
    <div ref={ref}>
      <p>My child element</p>
    </div>
  );
});

const ParentComponent = () => {
  const ref = useRef(null);
  useEffect(() => {
    console.log(ref.current.offsetWidth);
  }, []);

  return <MyComponent ref={ref} />;
};

As you can see, ForwardRefs offer a lot of flexibility and can help you write more reusable and modular code. Give them a try in your next React project!