Home > OS >  How to use the code above in React js using hooks
How to use the code above in React js using hooks

Time:11-16

document.getElementById("cards").onmousemove = e => {
  for(const card of document.getElementsByClassName("card")) {
    const rect = card.getBoundingClientRect(),
          x = e.clientX - rect.left,
          y = e.clientY - rect.top;

    card.style.setProperty("--mouse-x", `${x}px`);
    card.style.setProperty("--mouse-y", `${y}px`);
  };
}

I actually don't know how to use the above code in react js. so, if anyone knows please respond!

full source code link:

https://codepen.io/Hyperplexed/pen/MWQeYLW

CodePudding user response:

First of all, React does provide SyntheticEvents, so your onmousemove would probably look like this in React:

<div onm ouseMove={ yourEventHandler } />

I can see what you are trying to do is to set the children .card's properties when the mouse had moved. What you can do is to have useState() in the parent .cards container to store the latest mouse position, then pass that state as props into the children. Something like:

export function Cards() {
  const [mouseX, setMouseX] = useState(0);
  const [mouseY, setMouseY] = useState(0);

  const myOnMouseMove = (e)=> {
    // set your state using setMouseX(), setMouseY()
  }


  return (
    <div className='cards' onm ouseMove={myOnMouseMove}>
      <Card className='card' mouseX={mouseX} mouseY={mouseY} />
      <Card className='card' mouseX={mouseX} mouseY={mouseY} />
      ...
    </div>
  )
}

(Not real implementation, just the concept)

CodePudding user response:

to use Hook you need to handle with reference of element like this

  const CardRef = React.useRef(null);
  useShadow(CardRef);

  return <div ref={CardRef} className="card"  ></div>

And the hook would be something like this

import { useEffect } from 'react';

const useShadow = (reference: React.MutableRefObject<any>) => {
  useEffect(() => {
    const eventReference = (e) => {
      const rect = reference.current.getBoundingClientRect(),
        x = e.clientX - rect.left,
        y = e.clientY - rect.top;

      reference.current.style.setProperty('--mouse-x', `${x}px`);
      reference.current.style.setProperty('--mouse-y', `${y}px`);
    };

    if (reference.current) {
      const { current } = reference;
      current.addEventListener('mousemove', eventReference);
    }
    return () => {
      reference.current &&
        reference.current.removeEventListener('mousemove', eventReference);
    };
  }, [reference]);
};

export default useShadow;
  • Related