skip to Main Content

I can’t rewrite this code into a functional one using the useState and useEffect hooks. The neon cursor should be turned on by the button, but it does not move.

function App() {
  const [isCustomCursor, setIsCustomCursor] = React.useState();

  function handleChange() {
    setIsCustomCursor(!isCustomCursor);
  }

  return (
    <>
      <label>
        <input type="checkbox" onChange={handleChange}/>
        Включить неоновый курсор
      </label>
      {isCustomCursor && <NeonCursor/>}
    </>
  );
}

function NeonCursor() {
  const [top, setTop] = React.useState(0);
  const [left, setLeft] = React.useState(0);

  React.useEffect(() => {
    function handleMouseMove(event) {
      setTop({
        top: event.pageY,
      });
      setLeft({
        left: event.pageX,
      })        
    }

   document.addEventListener('mousemove', handleMouseMove);
    document.documentElement.classList.add('no-cursor');
      
    return () => {
    document.documentElement.classList.remove('no-cursor');
    document.removeEventListener('mousemove', handleMouseMove);
    };
  });
  
 
    return (
      <img
        src="https://code.s3.yandex.net/web-code/react/cursor.svg"
        width={30}
        style={{
          position: 'absolute',
          top: setTop,
          left: setLeft,
          pointerEvents: 'none',
        }}
      />
    );
  }

ReactDOM.render(<App/>, document.querySelector('#root'));

I hope u can solve my problem. I guess the problem is handleMouseMove function

2

Answers


  1. Chosen as BEST ANSWER

    I got it

        function NeonCursor() {
       const [position, setPosition] = React.useState({ top: 0, left: 0 });
    
      React.useEffect(() => {
        function handleMouseMove(event) {
          setPosition({
            top: event.pageY,
            left: event.pageX,
          });
        }
        
       document.addEventListener('mousemove', handleMouseMove);
        document.documentElement.classList.add('no-cursor');
          
        return () => {
        document.documentElement.classList.remove('no-cursor');
        document.removeEventListener('mousemove', handleMouseMove);
        };
      });
       
    

  2. useEffect takes a second argument which should be an empty array in this case. Like

    React.useEffect(function handler() {
     // code...
    }, []);
    

    The empty array means that the hook function runs once when the component is first rendered.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search