0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Autocomplete

Posted at
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;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?