어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ

useRef로 resize width 계산 후 class 넣기 본문

개발/🟦 React

useRef로 resize width 계산 후 class 넣기

비니_ 2025. 12. 1. 15:18
728x90

 

 

useRef 사용해서 DOM에 있는 태그를 잡아옴

그리고 .current를 붙여서 렌더링 된 태그를 잡음

const [isWrapped, setIsWrapped] = useState(false);
const userRestInfoBoxRef = useRef(null);
const firstItemRef = useRef(null);
const secondItemRef = useRef(null);
const [startIndex, setStartIndex] = useState(0);

const widthCheck = useCallback(() => {
    const userRestInfoBoxWidth = userRestInfoBoxRef.current?.offsetWidth - 18.5 || 0;
    const firstItemWidth = firstItemRef.current?.offsetWidth || 0;
    const secondItemWIdth = secondItemRef.current?.offsetWidth || 0;

    const sumItemWidth = firstItemWidth + secondItemWIdth;

    setIsWrapped(sumItemWidth > userRestInfoBoxWidth); // 부모 크기보다 크면 true

    console.log('hyobin_______test', userRestInfoBoxWidth, firstItemWidth, secondItemWIdth);
}, []);

useEffect(() => {
    widthCheck();
    window.addEventListener('resize', widthCheck);

    return () => window.removeEventListener('resize', widthCheck);
}, [widthCheck]);

useEffect(() => {
    widthCheck();
}, [startIndex]);
<div
    className={`vacation_status_box ${mobileDesign && isWrapped ? 'type_wrap' : ''}`}
    ref={userRestInfoBoxRef}
>
    <div className='d-flex flex-row justify-content-between align-items-center'>
       <div ref="firstItemRef">계속 바뀌는 너비</div>
       <div ref="secondItemRef">계속 바뀌는 너비2</div>        
        <div className='btn_arrow_box'>
            화살표
        </div>
    </div>
</div>

 

 

 

 

 

 

 

 

 

728x90
Comments