I want to change an element position base on the mouse position. I have a list of images displayed in a line using flex and I want to move the container (track) to the right when the mouse is moved to the left.
For this, I want to change the track style but I find it difficult. I tried using
navTrack.current.transform = `translateY(${-x})`;
but it throws an error.
This is the function:
const handleMouseMove = (e) => {
const x = e.clientX;
console.log(x);
navTrack.current.transform = `translateY(${-x})`;
};
The function is called on onm ouseMove.
CodePudding user response:
You may run into issues with this approach and when working in React it is generally recommended to not directly manipulate the DOM if you don't have to (and in this case, you don't). Instead you should do this in a React-like way. You do this by storing the mouse position in state and using it to set the transform property through the style
prop.
For example, here's a hook that would do this:
function useMouseMove() {
const [mouseX, setMouseX] = React.useState(0);
const onm ouseMove = React.useCallback((e) => {
setMouseX(e.clientX);
}, []);
return { mouseX, onm ouseMove };
}
And you can use it like this:
function MyComponent() {
const { mouseX, onm ouseMove } = useMouseMove();
React.useEffect(() => {
window.addEventListener("mousemove", onm ouseMove);
return () => window.removeEventListener("mousemove", onm ouseMove)
}, [onMouseMove]);
return (
<div style={{transform: `translateY(${-mouseX}px)`}}></div>
)
}
CodePudding user response:
You have to use style
property of the element when you want to add CSS. So in your case it would be:
navTrack.current.style.transform = `translateY(${-x})`;