In this article, we will see how to use multiple refs to a single component in React.

What are refs in react?

refs in react are used to access dom nodes or the components of a rendered elements. By default, we can create only one ref to a component but there might be a cases where we need to have more than one ref to a component.

Why we need multiple refs to a component?

There are several use cases where we might require multiple refs to a component. Like, If we have a complex component that has different parts, to access each part separately we may need to use the multi refs.

For example, if we have a form with multiple input fields, we can access each input field separately to set focus or validate the input using multi refs.

Example program on creating a multiple refs to a single component

function App() {
  const myRef = useRef(null);
  const hoverRef = useRef(null);
  const dragRef = useRef(null);

  const [isHovered, setHovered] = useState(false);
  const [isDragging, setDragging] = useState(false);

  useEffect(function() {
    hoverRef.current = myRef.current;
    dragRef.current = myRef.current;
  }, [myRef.current]);

  function handleMouseEnter() {
    setHovered(true);
  }

  function handleMouseLeave() {
    setHovered(false);
  }

  function handleDragStart() {
    setDragging(true);
  }

  function handleDragEnd() {
    setDragging(false);
  }

  return (
    <div 
      ref={myRef}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
      draggable
    >
      {isHovered ? 'Hovering' : 'Not Hovering'}
      {isDragging ? 'Dragging' : 'Not Dragging'}
    </div>
  );
}

Example:

In the above example, we create three different useRef() hooks to create three separate refs. We also created the two state variables using the useState() hook which keeps track of whether the component is being hovered or dragged.

We then use the useEffect() hook to set the current property of the hoverRef and dragRef to the current property of myRef. This allows us to access myRef from both hoverRef and dragRef.

We also define four separate event handlers for onMouseEnter, onMouseLeave, onDragStart, and onDragEnd to update the state variables for hovering and dragging.

We use the isHovered and isDragging state variables to display whether the component is being hovered or dragged and the draggable attribute on the div element to make it draggable.

Categorized in:

Tagged in: