์ฝ”๋”ฉ ๋ฉ”๋ชจ

<select>์—์„œ ์„ ํƒ๋œ ๊ฐ’ ๊ฐ€์ ธ์˜ค๊ธฐ : HTMLCollection

Dong _ hwa 2024. 1. 4. 23:41

 

 

select ๊ฐ’์„ value์— ๋„ฃ๊ธฐ๋งŒ ํ–ˆ์ง€ ํ•ด๋‹น value์—์„œ ๊บผ๋‚ด์˜จ ๊ฒƒ์ด ๊ธฐ์–ต์ด ์ž˜ ์•ˆ๋‚˜ ๋ฉ”๋ชจํ•ด๋†“๋Š”๋‹ค.

import { useState } from "react";

export default function App() {
  const initialFruitList = [
    { id: 1, name: "์‚ฌ๊ณผ", color: "RED" },
    { id: 2, name: "๋ฐ”๋‚˜๋‚˜", color: "YELLOW" },
    { id: 3, name: "์ฒด๋ฆฌ", color: "RED" },
    { id: 4, name: "๋ณต์ˆญ์•„", color: "PINK" },
    { id: 5, name: "ํฌ๋„", color: "PURPLE" },
  ];

  const [fruitList, setFruitList] = useState(initialFruitList);
  const [fruitDetail, setFruitDetail] = useState({
    selectedFruit: "",
    selectedFruitName: "",
  });

  return (
    <div className="App">
      <div>์ด ๊ณผ์ผ์€ {fruitDetail.selectedFruitName} ์ž…๋‹ˆ๋‹ค.</div>
      <select
        style={{
          width: "200px",
          border: "3px solid #ddd",
          height: "45px",
          backgroundColor: "white",
        }}
        onChange={(e) => {
          setFruitDetail((prev: any) => {
            return {
              ...prev,
              selectedFruit: e.target.value,
              selectedFruitName: "์—ฌ๊ธฐ",
            };
          });
        }}
        value={fruitDetail.selectedFruit}
      >
        <option value="">๊ณผ์ผ ์„ ํƒ</option>
        {fruitList?.map((fruit: any) => (
          <option key={fruit.id} value={fruit.id}>
            {fruit.name} ({fruit.color})
          </option>
        ))}
      </select>
    </div>
  );
}

(์˜ˆ์‹œ ๋ฐ์ดํ„ฐ)

 

์ฒ˜์Œ์—” ํ•จ์ˆ˜๋กœ ์ฐพ์•„์„œ ๊พธ์—ญ๊พธ์—ญ ๋„ฃ์—ˆ๋‹ค..

const getSelectedFruitName = (value) => {
    const selectedFruit = fruitList.find(
      (fruit) => fruit.id === parseInt(value)
    );
    return selectedFruit ? `${selectedFruit.name}` : "";
  };

 

ํ•ด์„œ  "์—ฌ๊ธฐ" ๋ถ€๋ถ„์— getSelectedFruitName(e.target.value)๋กœ ๋„ฃ์–ด์„œ ์‚ฌ์šฉํ–ˆ๋‹ค.

 

 

๋˜๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์€, HTMLCollection์„ ์ด์šฉํ•˜๋Š” ๊ฒƒ์ธ๋ฐ

HTMLCollection์—๋Š” ํ˜„์žฌ ์„ ํƒ๋œ ๊ฐ ์˜ต์…˜์— ๋Œ€ํ•œ ์ •๋ณด๊ฐ€ ํฌํ•จ๋˜์–ด ์žˆ๊ณ , ์ฃผ๋กœ ๋‹ค์ค‘ ์„ ํƒ์„ ์ง€์›ํ•˜๋Š” ๊ฒฝ์šฐ์— ์œ ์šฉํ•˜๊ฒŒ ์‚ฌ์šฉ๋œ๋‹ค๊ณ  ํ•œ๋‹ค.

..
	selectedFruitName: e.target.selectedOptions[0].text,
..

 

e.target.selectOptions ๋ฅผ ์ฝ˜์†”์— ์ฐ์–ด๋ณด๋ฉด,

 

 

์ด๋ ‡๊ฒŒ ๋‚˜์˜ค๊ธฐ ๋•Œ๋ฌธ์— ๊บผ๋‚ด์„œ ์“ฐ๋Š” ๊ฒƒ์ด๋‹ค.ใ…Ž

์ถ”๊ฐ€๋กœ ๋‚˜๋Š” ์•ž์˜ ๊ณผ์ผ์ด๋ฆ„ ๋ถ€๋ถ„๋งŒ ๋”ฐ์„œ ์“ธ ๊ฑฐ๊ธฐ ๋•Œ๋ฌธ์— ๋”ฐ๋กœ ๊ฐ€๊ณต( .split(' ')[0] )๋„ ์กฐ๊ธˆ์ถ”๊ฐ€ํ–ˆ๋‹ค.