[ react ] js파일에서 element height, width 변경하기

     

     

     

    오늘 마주한 문제는 이미지 크기만큼 크기를 가져와 평점과 더 보기 버튼을 담은 element 크기에 똑같이 설정하는 것이었다.

     

     

    ( 오직 평점과 더보기 버튼을 포스터 hover시 포스터 가운데에 두기 위함... )

    vanilla js에서만 살다가 react를 사용하니 css도 맘대로 할 수가 없었는데...

    js에선 element.clientWidth나 element.offsetWidth로  쉽게 가져와 style을 변경할 수 있었는데

    여기선 useRef를 사용해야한다.

     

    useRef를 통해서 img의 현재 높이와 넓이를 가져오고

    그걸 setHeight, setWidth함수를 통해 heigth, width 변수에 집어넣으며

    movie-hidden이라는 클래스를 가지는 div의 style에 이 변숫값으로 높이와 넓이를 설정해 놓는 방식이다.

     

    굳이 setTimeout함수를 써 높이와 넓이를 설정하는 함수를 0.2초 늦게 실행시킨 이유는

    분명 useEffect는 렌더링 된 후에 실행되는 걸로 알고 있는데...

    setTimeout함수가 없으면 imgRef.current.offsetWidth와 imgRef.current.offsetHeight이 0으로 나오기 때문 ㅠ...

    api로 데이터를 받아오는 시간 때문인지 뭔지는 도저히 모르겠어서 다음에 찾아봐야 할 것 같다.

    ( 0.1초는 또 너무 짧은 지 값이 0으로 나온다. )

     

    import React, { useEffect, useState } from "react";
    import { useRef } from "react";
    import { Link } from "react-router-dom";
    function Movie({id,title,rating,img}){
        const imgRef = useRef(null);
        const [height,setHeight] = useState(0);
        const [width,setWidth] = useState(0);
        const setSize = () => {
            setTimeout(()=>{
                setWidth(imgRef.current.offsetWidth)
                setHeight(imgRef.current.offsetHeight)
              }, 200);
        }
        useEffect(setSize,[])
        return (
            <div className="movie">
                <div className="movie-show">
                    <img src={img }  ref={imgRef}></img>
                    <span>{title}</span>
                </div>
                <div className="movie-hidden" style={{width:width,height:height}}>
                    <span>{rating}</span>
                    <button><Link to={process.env.PUBLIC_URL +`/movie/${id}`}>More</Link></button>
                </div>
            </div>
        );
    }
    export default Movie;

     

     

     

    하면 할수록 리액트가 싫고 정 떨어지는데 슬프다...🥲

    빨리 친해지고 좋은 점을 느껴봤으면 좋겠다...

    'React' 카테고리의 다른 글

    [ React ] React Hooks - useRef  (0) 2024.08.22
    [ React ] React Hooks - useMemo / Memoization  (0) 2024.08.21
    [ React ] 무한 렌더링 탈출기  (0) 2024.08.19
    [ React ] React Hooks - useCallback  (0) 2024.08.19

    댓글