import React, { useState } from "react";
import { Autocomplete, TextField } from "@mui/material";
interface AutocompleteItem {
itemId: number;
itemName: string;
}
const App: React.FC = () => {
// オプションデータ
const options: AutocompleteItem[] = [
{ itemId: 1, itemName: "Apple" },
{ itemId: 2, itemName: "Banana" },
{ itemId: 3, itemName: "Cherry" },
];
// 初期選択値 (例: Banana を選択状態にする)
const initialValue = options[1]; // { itemId: 2, itemName: "Banana" }
// State管理
const [selectedItem, setSelectedItem] = useState<number>(initialValue.itemId);
return (
<div style={{ width: 300 }}>
<Autocomplete
options={options}
getOptionLabel={(option) => option.itemName} // itemNameを表示
isOptionEqualToValue={(option, value) => option.itemId === value.itemId} // 一意の比較
value={options.find((item) => item.itemId === selectedItem) || null} // 初期選択
onChange={(event, newValue) => {
if (newValue) {
setSelectedItem(newValue.itemId); // itemIdをStateに保存
}
}}
renderInput={(params) => (
<TextField {...params} label="Select an item" variant="outlined" />
)}
/>
<div style={{ marginTop: 16 }}>
<strong>Selected Item ID:</strong> {selectedItem}
</div>
</div>
);
};
export default App;
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme