React - hover기능 구현하기

da.circle·2022년 10월 30일
3

리액트에서 마우스hover했을 때 클래스를 추가하는 방법

출처 ) bobbyhadz.com/blog/react-add-css-class-on-hover

//App.js파일
function App() {
  const [isHovering, setIsHovering] = useState(false);

  const handleMouseOver = () => {
    setIsHovering(true);
  };

  const handleMouseOut = () => {
    setIsHovering(false);
  };
  return (
    <div>
      <div>
        <div
          className={isHovering ? "grow" : ""}
          onMouseOver={handleMouseOver}
          onMouseOut={handleMouseOut}
        >
          Hover
        </div>
      </div>
    </div>
  );
}
/*App.css파일*/
div {
  width: 100px;
  height: 100px;
  background-color: aliceblue;
  text-align: center;
  line-height: 100px;
  transition-property: width, height;
  transition-duration: 1s, 1s;
}

.grow {
  width: 200px;
  height: 120px;
}

  • 커서가 div 안으로 이동되면
  1. handleMouseOver 함수가 호출된다.
  2. isHovering이 true로 변경된다.
  3. div의 className에 "grow"가 추가된다.

  • 커서가 div에서 밖으로 빠져나오면
  1. handleMouseOut 함수가 호출된다.
  2. isHovering이 false로 변경된다.
  3. className에 아무것도 추가되지 않는다.
profile
프론트엔드 개발자를 꿈꾸는 사람( •̀ ω •́ )✧

0개의 댓글