날아라김지원
article thumbnail

브라우저 사이즈가 바뀜에 따라 NavBar의변경, 하단 Footer의 변경등을 구현하고 싶었다.

 

순수 바닐라 자바스크립트의 window.innerWitdh를 조절하는것도 가능하지만 만들어진 훅이 있길래 가져와서 사용했다.

 

현재 부트스트랩 Grid System을 사용중이고 

해당 사이즈를기준으로 경계를 주어 사용해 주었다.

 

그리고 아래와같이 useState와 useEffect까지 사용해 구현했다.

 

.......

  const size = useWindowSize();
  // const [size,setSize] = useState(size)
  const [sizeon,setSizeon] = useState(false)
  useEffect(()=>{
    if(size.width<=576){
      console.log('핸드폰화면Footer')
      setSizeon(true)
    }else if(size.width>567){
      setSizeon(false)
    }
    console.log(size.width)
    console.log(size.height)
  },[size])
  
  return (
  .........

1.자바스크립트 코드

import { useState, useEffect } from "react";
// Usage
function App() {
  const size = useWindowSize();
  return (
    <div>
      {size.width}px / {size.height}px
    </div>
  );
}
// Hook
function useWindowSize() {
  // Initialize state with undefined width/height so server and client renders match
  // Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });
  useEffect(() => {
    // Handler to call on window resize
    function handleResize() {
      // Set window width/height to state
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }
    // Add event listener
    window.addEventListener("resize", handleResize);
    // Call handler right away so state gets updated with initial window size
    handleResize();
    // Remove event listener on cleanup
    return () => window.removeEventListener("resize", handleResize);
  }, []); // Empty array ensures that effect is only run on mount
  return windowSize;
}

 

2.타입스크립트 코드

import { useState, useEffect } from "react";
// Define general type for useWindowSize hook, which includes width and height
interface Size {
  width: number | undefined;
  height: number | undefined;
}
// Usage
function App() {
  const size: Size = useWindowSize();
  return (
    <div>
      {size.width}px / {size.height}px
    </div>
  );
}
// Hook
function useWindowSize(): Size {
  // Initialize state with undefined width/height so server and client renders match
  // Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
  const [windowSize, setWindowSize] = useState<Size>({
    width: undefined,
    height: undefined,
  });
  useEffect(() => {
    // Handler to call on window resize
    function handleResize() {
      // Set window width/height to state
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }
    // Add event listener
    window.addEventListener("resize", handleResize);
    // Call handler right away so state gets updated with initial window size
    handleResize();
    // Remove event listener on cleanup
    return () => window.removeEventListener("resize", handleResize);
  }, []); // Empty array ensures that effect is only run on mount
  return windowSize;
}

- 참고한사이트

https://usehooks.com/useWindowSize/

 

useWindowSize

 

usehooks.com

https://www.npmjs.com/package/react-window-size

 

react-window-size

React HOC that passes browser window size to wrapped component. Latest version: 1.2.2, last published: 4 years ago. Start using react-window-size in your project by running `npm i react-window-size`. There are 14 other projects in the npm registry using re

www.npmjs.com

https://jcon.tistory.com/121

 

react get browser size

react는 직접적으로 dom을 조작하는 것을 지양한다. 태생 자체가 virtual dom을 사용하여 효율적인 렌더링을 하기 위해 만들어 졌기 때문이다. 하지만 dom을 조작해야하는 상황이 있다. 브라우저의 widt

jcon.tistory.com

https://sometimes-n.tistory.com/22

 

[javascript] 윈도우 창 크기 (window.outerWidth, window.outerHeight, window.outerHeight, window.innerWidth, innerHeight)

자바스크립트에서 윈도우 창 크기에 대해 알아보겠습니다. 익스플로러, 크롬, 파이어폭스, 오페라 모두 같은 값을 출력하는 윈도우 창크기는 window.outerWidth, window.outerHeight, window.outerHeight, window...

sometimes-n.tistory.com

->브라우저 크기 설명이 잘되어 있는 사이트

'React' 카테고리의 다른 글

리액트 조건문  (0) 2022.04.27
axios 여러개 요청하기 (멀티 리퀘스트)  (0) 2022.04.02
Mui 스타일 설정  (0) 2022.03.31
handlechange 사용  (1) 2022.03.25
React 페이지네이션 구현하기 (Mui이용)  (0) 2022.03.25
profile

날아라김지원

@flykimjiwon

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!