React - state

No.8·2023년 1월 18일
0

React

목록 보기
1/3

React는 Frontend 개발을 위한 javascript 라이브러리이다

기존 vanilla JS 이용해 html페이지를 작성해보면

  • vanilla.html
<!DOCTYPE html>
<html lang="en">
  <body>
    <span>total click: 0</span>
    <button id="btn">Click me</button>
  </body>
  <script>
    let counter = 0;
    const button = document.getElementById("btn");
    const span = document.querySelector("span");
    function handleClick() {
      counter += 1;
      span.innerText = `Total click: ${counter}`;
    }
    button.addEventListener("click", handleClick);
  </script>
</html>
  1. 태그를 생성
  2. id 혹은 className을 지정
  3. 아래 script에서 해당 id 혹은 className을 ㅗ태그를 가져온 후 이벤트를 붙이는 형식

하지만 이를 React로 다시 쓰면

<!DOCTYPE html>
<html lang="en">
  <body>
    <div id="root"></div>
  </body>
  <script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script> //React Element를 생성할 수 있게 해준다
  <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script> // Element들은 html Dom에 추가할 수 있게 해준다
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> // jsx를 js로 변환해준다
  <script type="text/babel">  // babel 사용을 위해 type을 text/babel로 변경해준다
    const root = document.getElementById('root'); // body에 앞으로 만들 요소들을 넣기 위해 body에 있는 div를 불러온다
    function App() {       // state 관리
      const [counter, setCounter] = React.useState(0); // useState는 배열을 반환해준다 [data, function] 형식으로
      const onClick = () => {  // useState의 1번 인덱스 즉 function은 실행 시 리렌더링해준다
        setCounter(counter + 1)  // setCounter라는 이름의 useState의 modify함수를 실행하며 변화하는 data 값은 counter이다 
      }
      return (
        <div>
          <h3>total click: {counter}</h3>  // 위에서 지정한 변수를 { } 로 받아올 수 있다
          <button onClick={onClick}>Click me</button>
        </div>
      );
    }
    ReactDOM.render(<App />, root); // 초기 렌더링
  </script>
</html>

바닐라 JS에서의 단계를 단순하게 줄일 수 있다는 장점이 있다

JSX

jsx는 javascript에 XML을 추가 확장한 문법이다.
babel을 사용하여 javascript로 변환하게 된다
JSX는 하나의 파일에 자바스크립트와 HTML을 동시에 작성하여 편리하다.
자바스크립트에서 HTML을 작성하듯이 하기 때문에 가독성이 높고 작성하기 쉽다

state로 단위변환기 만들어보기

<!DOCTYPE html>
<html lang="en">
  <body>
    <div id="root"></div>
  </body>
  <script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script>
  <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  <script type="text/babel">

body가 결국엔 아래쓰일 코드들이 렌더링되어 보여지게될 DOM이다

function 하나가 하나의 컴포넌트이다

function MinutesToHours() { // 분 시간 변환 함수
      const [amount, setAmount] = React.useState(0) 
      const [inverted, setInverted] = React.useState(false)
      const onChange = (event) => {
        setAmount(event.target.value)
      }
      const reset = () => setAmount(0) // setAmount를 이용해 amount를 0으로 초기화
      const onInvert = () => {	// inverted를 바꾸는 함수
        reset()
        setInverted((current) => !current) // setInverted이용해 inverted값 변환
      }
      return (
        <div> {/* DOM구조여야 하기에 하나의 요소에 담아야한다*/}
          <div>
            {/* for는 예약어라서 htmlfor를 사용해야 한다*/}
            <label htmlfor='minutes'>Minutes</label> 
            <input
              value={inverted ? amount * 60 : amount} // 삼항연산자
              id='minutes'
              placeholder='Minutes'
              type='number'
              onChange={onChange}
              disabled={inverted}
            />
          </div>
          <div>
            <label htmlfor='hours'>Hours</label>
            <input
              value={inverted ? amount : Math.round(amount / 60)}
              id='hours'
              placeholder='Hours'
              type='number'
              onChange={onChange}
              disabled={!inverted}
            />
          </div>
          <button onClick={reset}>Reset</button>
          <button onClick={onInvert}>
            {inverted ? 'Turn back' : 'Invert'}
          </button>
        </div>
      )
    }

위는 분 시간 변환 함수이다 이를 html에 보이기 위해서는

function App() {
      const [index, setIndex] = React.useState('xx')
      const onSelect = (event) => {
        setIndex(event.target.value)
      }
      console.log('render w/', index)
      return (
        <div>
          <h1>Super Converter</h1>
          <select value={index} onChange={onSelect}>
            <option value='xx'>select option</option>
            <option value='0'> Minute & Hours </option>
            <option value='1'> Km & Miles </option>
          </select>
          <hr />
          {index === 'xx' ? 'please select yout unit' : null}
          {index === '0' ? <MinutesToHours /> : null}
          {index === '1' ? <KmToMiles /> : null}
        </div>
      )
    }
    const root = document.getElementById('root')
    ReactDOM.render(<App />, root) // 결국 렌더링하는 것은 App
  </script>
</html>

body 태그에 넣기 위해 최상위 컴포넌트 역할을 하는 app에 써야한다

profile
88888888

0개의 댓글