프론트엔드 첫걸음

CSS 속성 변경을 setProperty로 할것인가- useState + inline style로 할것인가 본문

로그/문제상황

CSS 속성 변경을 setProperty로 할것인가- useState + inline style로 할것인가

차정 2022. 4. 3. 14:40

 

input 박스에서 색을 변경할 때마다 화면 색이 바뀌게 하려고 한다.
바꾸려는 화면은 상위컴포넌트(App)에, 바뀌게 하는 input 태그는 하위 컴포넌트(Navbar)에 있는 상황이다.
하위컴포넌트에 prop으로 콜백함수(bgColorHandler)를 넘기려고 한다.
이 때 콜백함수는 style.setProperty를 사용해야 할까 ,
아니면 useState로 상위컴포넌트에서 화면색에 대한 변수를 관리한 다음 inline으로 style을 넣는게 나을까?
아무튼 둘 다 되긴 한다. 

 

 

 

- 코드를 단순화해서 올리지 않고 그대로 복붙하는 이유는.. 개린이에게는 nodeList를 forEach돌리는 것도 새삼스러운 코드이기 때문에... (님들 nodeList와 array의 차이점 알아? 난 몰랐어..) 

 

 

setProperty로 DOM을 조작해서 바꾸는 방법

App.jsx

import React, { useState, useEffect } from 'react';
import styles from './App.module.css';
import Navbar from './Navbar';

function App() {
  //const [bgColor, setBgColor] = useState();

  const bgColorHandler = (selectedColor) => {
    // console.log(selectedColor);
    const doms = document.querySelectorAll(
      `.${styles.App}, .${styles.colorPickerGuide}`
    );
    doms.forEach((dom) =>
      dom.style.setProperty('--selectedColor', selectedColor)
    );
    // setBgColor(selectedColor);
  };

  useEffect(() => {}, []);
  return (
    <div style={{ height: '100vh' }}>
      <Navbar colorSelector={bgColorHandler}></Navbar>
      <div className={`${styles.colorPickerGuide}`}>guide message</div>
      <div className={`${styles.App}`}>TEST 중</div>
    </div>
  );
}

export default App;

 

App.module.css

:root {
  --selectedColor: white;
}

.App {
  display: flex;
  align-items: center;
  box-sizing: border-box;
  height: 100%;
  width: 100%;
  background: var(--selectedColor);
}

.colored {
  background: var(--selectedColor);
}

.colorPickerGuide {
  background: var(--selectedColor);
  text-align: right;
  padding: '10px';
  color: red;
  margin: '20px';
}

 

 

useState로 변수를 관리해서 inline으로 스타일 넘겨주는 방법

App.jsx

import React, { useState, useEffect } from 'react';
import styles from './App.module.css';
import Navbar from './Navbar';

function App() {
  const [bgColor, setBgColor] = useState();

  const bgColorHandler = (selectedColor) => {
    setBgColor(selectedColor);
  };

  useEffect(() => {}, []);
  return (
    <div style={{ height: '100vh' }}>
      <Navbar colorSelector={bgColorHandler}></Navbar>
      <div
        className={`${styles.colorPickerGuide}`}
        style={{ backgroundColor: bgColor }}
      >
        guide message
      </div>
      <div className={`${styles.App}`} style={{ backgroundColor: bgColor }}>
        TEST 중
      </div>
    </div>
  );
}

export default App;

 

 

 

 

 

난 돔을 조작하는 방법이 더 깔끔해보인다. 그냥 내 맘~~~~

뭔가 더 깔끔하게 할 수 있는 방법이 있을 것 같은데 아직은 잘 모르겠다.

css도 변수로 관리한다는 점이 너무 신기하고 멋지게 느껴진다.

 

 

 

 

7/25 
위 코드는 리액트 공부 초반에 javascript30 에 나온 예제를 리액트 스타일로 바꿔본 것이다.
다시보니까 state로 관리하는게 더 나아보인다.
그것이 리액트니까...

이 짤을 넣지 않고는 못 배기겠는 밈중독자