React TS useRef() hook

This hook is useful when we are trying to read some input field or when we just need the reference to the element for getting size or other properties.

How to use it?

imagine we are trying to make a tooltip under some element when user hovers over it

  • make ButtonTooltip component with props tooltipText and children
  • create variable that holds the reference-buttonRef
  • link the buttonRef to the button via the ref prop
  • add onMouseEnter and onMouseLeave
  • in logic for handling mouse enter reference it, and get the properties you need
JavaScript
import React, { useRef } from 'react'

function ButtonTooltip({ tooltipText, children }: { tooltipText: string, children: React.ReactNode }) {
    const buttonRef = useRef<HTMLButtonElement | null>(null);

    const handleMouseEnter = () => {
        if (buttonRef.current) {
            const buttonRect = buttonRef.current.getBoundingClientRect();
            const tooltip = document.createElement('div');
            tooltip.className = 'tooltip';
            tooltip.textContent = tooltipText;
            tooltip.style.position = 'absolute';
            tooltip.style.left = buttonRect.left + 'px';
            tooltip.style.top = buttonRect.bottom + 'px';
            document.body.appendChild(tooltip);
        }
    };

    const handleMouseLeave = () => {
        const tooltip = document.querySelector('.tooltip');
        if (tooltip) {
            document.body.removeChild(tooltip);
        }
    };

    return (
        <button
            ref={buttonRef}
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
        >
            {children}
        </button>

    );
};

export default ButtonTooltip


and now we can use it in our app

JavaScript
function App() {

  return (
    <div className="App" style={
      // center of the screen
      {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh'
      }
    }>
      <ButtonTooltip tooltipText="Tooltip text" >
        Hover me
      </ButtonTooltip>
    </div>
  );
}

export default App;

I hope that this simple tutorial did explain the possible use case of useRef() hook.
Happy coding


Posted

Comments

Leave a Reply

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