Framework/React

[React] useState๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ† ๊ธ€ ๋ฒ„ํŠผ ๊ตฌํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ• Button toggle on off

yuri lee 2023. 3. 11. 15:25
๋ฐ˜์‘ํ˜•

Intro

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” react ๋ฆฌ์•กํŠธ์—์„œ ํ† ๊ธ€ ๋ฒ„ํŠผ์„ ๊ตฌํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 

How to solve the problem

์ €๋Š” ํ† ๊ธ€ ๋ฒ„ํŠผ์„ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด์„œ useState hook์„ ์‚ฌ์šฉํ•˜์˜€์Šต๋‹ˆ๋‹ค.

useState hook is used to initialize with initial value and function which changes its value on click event handler.

 

์šฐ์„  ์ฒ˜์Œ ํ† ๊ธ€๋ฒ„ํŠผ์˜ on/off ์ƒํƒœ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” state๋ฅผ ๋งŒ๋“ค์–ด์ค๋‹ˆ๋‹ค. 

const [isOff, setIsOff] = useState(true);

 

์ดํ›„ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•  ๋•Œ๋งˆ๋‹ค, ํ•ด๋‹น state๋ฅผ ์‚ฌ์šฉํ•ด์ค๋‹ˆ๋‹ค. on/off ์ƒํƒœ์— ๋”ฐ๋ผ css class๋„ ๋‹ค๋ฅด๊ฒŒ ์ ์šฉํ•ด์ค„ ์ˆ˜ ์žˆ๊ฒ ์ฃ ?

  <button onClick={() => setIsOff(!isOff)}>{ isOff ? 'ON' : 'OFF' }</button>

 

์•„๋ž˜๋Š” ์ „์ฒด ์†Œ์Šค์ž…๋‹ˆ๋‹ค. ์ฐธ๊ณ ํ•ด์ฃผ์„ธ์š” :)

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

const ToggleButtonOnOff = () => {
  const [isOff, setIsOff] = useState(true);

  return (
    <button onClick={() => setIsOff(!isOff)}>{ isOff ? 'ON' : 'OFF' }</button>
  );
}

ReactDOM.render(
  <ToggleButtonOnOff />,
  document.getElementById('root')
);
๋ฐ˜์‘ํ˜•