<select>์์ ์ ํ๋ ๊ฐ ๊ฐ์ ธ์ค๊ธฐ : HTMLCollection
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] )๋ ์กฐ๊ธ์ถ๊ฐํ๋ค.