Skip to content Skip to sidebar Skip to footer

Using Multiple Refs On A Single React Element

I'm using the useHover() react hook defined in this recipe. The hook returns a ref and a boolean indicating whether the user is currently hovering over element identified by this r

Solution 1:

A React ref is really nothing but a container for some mutable data, stored as the current property. See the React docs for more details.

{
  current: ... // my ref content
}

Considering this, you should be able to sort this out by hand:

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

  const [hoverRef, isHovered] = useHover();
  const [dragRef, isDragging] = useDrag();

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

  return (
    <div ref={myRef}>
      {isHovered ? 'Hovering' : 'Not Hovering'}
      {isDragging ? 'Dragging' : 'Not Dragging'}
    </div>
  );
}

Post a Comment for "Using Multiple Refs On A Single React Element"