[REACT] 실시간 화면 너비 구하기(with useEffect) 본문

code/React.js

[REACT] 실시간 화면 너비 구하기(with useEffect)

남우p 2022. 3. 18. 17:32
import React, { useState, useEffect, useRef } from 'react';

// 브라우저 넓이에 따른 앱 다운로드 링크 변경
  const [browserWidth, setBrowserWidth] = useState<number>(0);
  const resizeTimer = useRef<any>(null);

  useEffect(() => {
    const handleResize = () => {
      if (resizeTimer.current !== null) return;
      resizeTimer.current = setTimeout(() => {
        resizeTimer.current = null;
        setBrowserWidth(window.innerWidth);
      }, 200);
    };
    window.addEventListener('resize', handleResize);
    console.log(browserWidth);
    return () => {
      window.addEventListener('resize', handleResize);
    };
  }, [browserWidth]);

앞으로 화면 구현에서 굉장히 많이 사용될 듯한 코드입니다.

browser로 너비를 받아서 별도의 코드를 구현하면 됩니다.

 

시행착오

1. handleResize를 useEffect 바깥에서 구현

 : useEffect의 deps로 설정한 browserWidth 부분 에러가 남

 => useEffect 안에서 사용된 것만 deps로 인정하기 때문에 문제가 됨.

      handleResize를 useEffect 안으로 이동

 

비슷한 경우 : 

import React, { useState, useRef, useEffect } from 'react';

const Area = () => {
  const [scrollY, setScrollY] = useState(0);
  const scrollTimer = useRef<any>(null);
  const floatingBtn = useRef<any>();
  useEffect(() => {
    const handlerScrollY = () => {
      if (scrollTimer.current !== null) return;
      scrollTimer.current = setTimeout(() => {
        scrollTimer.current = null;
        setScrollY(window.pageYOffset);
      }, 500);
    };
    const handlerScrollAction = () => {
      window.addEventListener('scroll', handlerScrollY);
      if (floatingBtn.current !== undefined) {
        if (!!scrollTimer && scrollY > 290) {
          floatingBtn.current.classList.add('active');
        } else {
          floatingBtn.current.classList.remove('active');
        }
      }
    };
    handlerScrollAction();
    return () => handlerScrollAction();
  }, [scrollY, scrollTimer]);

  return (
      <div className="floating-btn" ref={floatingBtn}>
        <a href="" className="new-btn type1">
          서비스 신청하기
        </a>
      </div>
    );
  };
  
  export default Area;

 

  .floating-btn {
    position: fixed;
    z-index: 9999;
    visibility: hidden;
    opacity: 0;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 20px 20px;
    will-change: visibility, opacity;
    transition-property: visibility, opacity;
    transition-duration: 0.3s;
    transition-timing-function: cubic-bezier(0.07, 0.73, 0.71, 1.03);
    &.active {
      visibility: visible;
      opacity: 1;
    }

버튼이 스크롤 위치에 따라 나타났다 사라질 수 있도록 설정하는 코드이다.

 

Comments