Home > Software engineering >  How can I call Variable outside function | Reactjs
How can I call Variable outside function | Reactjs

Time:08-14

I wanna change style when mouse move over an element but It gives me "undefined" so How can I get variable outside function scope

      let screenWidth = window.innerWidth;
  let screenHeight = window.innerHeight;
  let maxDegrees = 45;
  const handleMove = (event) => {
    let mouseX = event.pageX/screenWidth;
    let mouseY = event.pageY/screenHeight;
    let yDegrees = (mouseX*maxDegrees)-0.5*maxDegrees;
    let xDegrees = -0.5*((mouseY*maxDegrees)-0.5*maxDegrees);
    console.log({transform: 'rotateY('  yDegrees   'deg) rotateX('   xDegrees  'deg)' });
  };

and there is the code of style

<div className='section two' id="About" onm ouseMove={handleMove}>
    <div  style={{transform: 'rotateY('  yDegrees   'deg) rotateX('   xDegrees  'deg)' }}>

Thanks in advance ♥

CodePudding user response:

You can set a state inside the function, and use this state inside the JSX.

like so:

const [degree, setDegree] = useState();

  const handleMove = (event) => {
    let mouseX = event.pageX/screenWidth;
    let mouseY = event.pageY/screenHeight;
    let yDegrees = (mouseX*maxDegrees)-0.5*maxDegrees;
    let xDegrees = -0.5*((mouseY*maxDegrees)-0.5*maxDegrees);
    setDegree({ xDegrees, yDegrees });
  };

  ...
  <div  style={{transform: 'rotateY('  degree?.yDegrees || 0   'deg) rotateX('   degree?.xDegrees || 0  'deg)' }}>
  ...

CodePudding user response:

instead of creating a function, make an object:

let obj={
    mouseX: event.pageX/screenWidth;
    mouseY: event.pageY/screenHeight;
    yDegrees: (mouseX*maxDegrees)-0.5*maxDegrees;
    xDegrees: -0.5*((mouseY*maxDegrees)-0.5*maxDegrees);
}

and in the jsx you can do something like:

<div className='section two' id="About" onm ouseMove={handleMove}>
    <div  style={{transform: 'rotateY('  obj.yDegrees   'deg) rotateX('   obj.xDegrees  'deg)' }}>

however, if some value is going to change inside the object while the component is mounted, and you want to update some values on screen (which means on re-render) then i suggest using react "state", so just store obj as a state, with a setter:

import {useState} from 'react';

const [obj,setObj] = useState({
    mouseX: event.pageX/screenWidth;
    mouseY: event.pageY/screenHeight;
    yDegrees: (mouseX*maxDegrees)-0.5*maxDegrees;
    xDegrees: -0.5*((mouseY*maxDegrees)-0.5*maxDegrees);
    
}

  • Related