본문 바로가기

리액트

React 반응형으로 창 크기 조절(비율 고정)

<div id="root"></div>

<index.html>

const root = ReactDOM.createRoot(document.getElementById('root'));
 
root.render(
  <Provider store={store}>
    <App socket={socket} this={root._internalRoot.containerInfo.style}/>
  </Provider>
);

<index.js>

-리액트는 기본적으로  이 root란 id를 가진 요소에 그림을 그린다(본문과 다르더라도 너께 맞다 맞다).

<div id="Range">
      <div id="root"></div>
</div>

<index.html>

-그렇기에  이렇게 바꾸어도 root안에서 렌더링이 가능하단 뜻이 된다.

-이제 css 설정을 해야한다, 이제부터 잘 따라오도록 한다.

 
html{
  height: 100%;
  background-color: black;
}
body {
  background-color: black !important;
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  height: -webkit-fill-available;
  height: fill-available;
  margin: 0;
  padding: 0;
}
#root{
  position: relative;
  width: 1920px;
  height: 1080px;
}

<index.css>

-자 이제 리액트내에서 WindowSize 란 새로운 함수를 이용해서 사이즈를 조절할 것이다.

-우선 WindowSize.js 파일을 만들고 아래 코드를 삽입하자.

export function WindowSize(standardWidth,standardHeight,gubun,android) {
  const body = document.querySelector("body");
  const root = document.querySelector("#Range");
 
    root.style.width = `${standardWidth}px`;
    root.style.height = `${standardHeight}px`;
 
   
    let width = body.clientWidth;
    let height = (width * standardHeight) / standardWidth;

    if (height > body.clientHeight) {
      height = body.clientHeight;
      width = (height * standardWidth) / standardHeight;

      root.style.zoom = width / standardWidth;
 
    }
    else
    {
 
        root.style.zoom = height / standardHeight;
    }
 
  
}

<WindowSize.js>

-나는 반응형을 만들기 위해 화면의 넓이와 높이를 계산하여 16:9의 비율로 보여주기위해 zoom 이란 css속성을 이용하여 만들었다.

-이 공식은 F12(개발자도구)를 열어서 본인의 화면에 존재하는 id=Ragne 인 요소의 zoom 을 나중에 클릭해보고 이해하면 편하다.

-변수명 태클걸지마라 귀찮아서 안바꾼거다.

import { WindowSize } from '../WindowSize.js';
function App(props) {
  const width = 1920;
  const height = 1080;
//사이즈조절
  useEffect(()=>{
   
    const handleSize = (event = null) => {
          WindowSize(width, height,'PC90',  'no');  
    }
   
    window.addEventListener('resize',handleSize);
    handleSize();
    return ()=>{
      window.removeEventListener('resize',handleSize);  
    };
   
  },[뭐였더라 기억이 안나네 아무것도 안적어도 되거나 window.innerWidth,window.innerHeight 적으셈]);
 
}

<App.js>

-이렇게까지 하고 리액트를 실행해보면 정상적으로 화면의 넓이에 따라 비율이 새로 조정되어서 나타날 것이다.

 

이상 더 자세한 심화과정(in Mobile, IOS, AOS 등)은 댓글에서 많은이가  요청하면 알려주겠다.