๊ฐœ๋ฐœ ๐Ÿพ/ReactJS

React ์—์„œ select ์‚ฌ์šฉํ•˜๊ธฐ

JOTOKKI 2021. 6. 14. 10:30
728x90

์…€๋ ‰ํŠธ๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ๋‹ค์Œ๊ณผ ๊ฐ™์ด jsx ๊ตฌ๋ฌธ์„ ๋งŒ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค.

<select className="w150" onChange={handleChangeSelect}>
  <option value="1" >0.1ํ†ค</option>
  <option value="2">0.2ํ†ค</option>
  <option value="3">0.3ํ†ค</option>
  <option value="4" selected={true}>0.4ํ†ค</option> {/* ์„ ํƒํ•˜๋ ค๋˜ ๋ถ€๋ถ„! */}
  <option value="5">0.5ํ†ค</option>
</select>

 

๊ธฐ์กด html ์—์„œ ๋””ํดํŠธ ์˜ต์…˜์„ ์„ ํƒํ•˜๋ ค๋ฉด option ํƒœ๊ทธ์•ˆ์— selected ์†์„ฑ์„ ์ฃผ์–ด ๋™์ž‘ ํ•˜์˜€์Šต๋‹ˆ๋‹ค. 

ํ•˜์ง€๋งŒ ๋ฆฌ์•กํŠธ์—์„œ ์ด์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•˜๋ ค๊ณ  ํ•œ๋‹ค๋ฉด, ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์—๋Ÿฌ๋ฅผ ๋ฑ‰์–ด๋ƒ…๋‹ˆ๋‹ค.

React์—์„œ๋Š” selected ๋Œ€์‹  value๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. 

๋˜ํ•œ selected์˜ ์„ ํƒ๋œ value ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๋ ค๋ฉด, onChange๋ฅผ ์‚ฌ์šฉํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค.

์œ„์˜ ์†Œ์Šค๋ฅผ ์ˆ˜์ •ํ•ด ๋ณด๋ฉด ์ด๋ ‡์Šต๋‹ˆ๋‹ค.

 

<select className="w150" onChange={handleChangeSelect} value={'4'}>
  <option value="1" >0.1ํ†ค</option>
  <option value="2">0.2ํ†ค</option>
  <option value="3">0.3ํ†ค</option>
  <option value="4">0.4ํ†ค</option>
  <option value="5">0.5ํ†ค</option>
</select>

 

์œ„์˜ ๋‚ด์šฉ์œผ๋กœ๋„ ์†Œ์Šค๋ฅผ ์ ์šฉํ•˜๊ธฐ ์–ด๋ ต๋‹ค๋ฉด ์•„๋ž˜์˜ ๋‚ด์šฉ์„ ๋ด์ฃผ์„ธ์š”!

export default function App() {
  const selectList = ["apple", "banana", "grape", "orange"];
  const [Selected, setSelected] = useState("");

  const handleSelect = (e) => {
    setSelected(e.target.value);
  };

  return (
    <div className="App">
      <h1>Select in React</h1>
      <div>
        <select onChange={handleSelect} value={Selected}>
          {selectList.map((item) => (
            <option value={item} key={item}>
              {item}
            </option>
          ))}
        </select>
        <hr />
        <p>
          Selected: <b>{Selected}</b>
        </p>
      </div>
    </div>
  );
}

 

Selected ๋Š” ์„ ํƒ๋œ option์ด ๋“ค์–ด๊ฐ‘๋‹ˆ๋‹ค. 

onChange๋Š” ์„ ํƒ๋œ option์˜ value ๊ฐ’์„ e.target.value ๋กœ ๋ฐ›์€ ํ›„, Selected ์— setState ์‹œ์ผœ์ค๋‹ˆ๋‹ค. 

๋งŒ์•ฝ ์ฒ˜์Œ๋ถ€ํ„ฐ grape๊ฐ€ ์„ ํƒ ๋œ ์ฑ„๋กœ ์„ค์ • ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด Selected ๋ถ€๋ถ„์— default ๊ฐ’์„ ๋„ฃ์–ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค. 

const [Selected, setSelected] = useState("grape");

 

 

 

๋ฐ˜์‘ํ˜•