Riten Vagadiya Software Engineer

React Hook to calculate distance between div elements

Here is a simple React Hook in TypeScript to calculate the distance between two div elements:

function useDistance(
    ref1: React.RefObject<HTMLDivElement>, 
    ref2: React.RefObject<HTMLDivElement>
  ): number | null {
  const [distance, setDistance] = useState<number | null>(null);

  useEffect(() => {
    if (ref1.current && ref2.current) {
      const rect1 = ref1.current.getBoundingClientRect();
      const rect2 = ref2.current.getBoundingClientRect();
      const dx = rect1.left - rect2.left;
      const dy = rect1.top - rect2.top;
      const distance = Math.sqrt(dx * dx + dy * dy);
  }, [ref1, ref2]);

  return distance;

export default useDistance;

We define a custom hook called useDistance with TypeScript type definitions that takes two React.RefObject objects as arguments and returns the distance between the two div elements as a state variable. The useEffect hook inside the useDistance hook is responsible for calculating the distance between the two elements whenever they change.

Here is an example of how we use the hook:

import { useRef } from 'react';
import useDistance from './useDistance';

function ExampleDistanceCalculator() {
  const div1Ref = useRef<HTMLDivElement>(null);
  const div2Ref = useRef<HTMLDivElement>(null);
  const distance = useDistance(div1Ref, div2Ref);
  const style1 = {
    width: '50px', 
    height: '50px'
  const style2 = {
    width: '50px',
    height: '50px',
    marginLeft: '100px',
    marginTop: '100px',

  return (
      { distance && <p>Distance: {distance.toFixed(2)}</p> }

export default ExampleDistanceCalculator;

We then use the useDistance hook inside the ExampleDistanceCalculator component to calculate the distance between two div elements using their ref objects. We render the two div elements and the distance between them.

You can use the example ExampleDistanceCalculator component like this:

<ExampleDistanceCalculator />