LoginSignup
3
0

MUI(Material UI)のAutocompleteでEncountered two children with the same keyのエラーが出る時の対処法

Last updated at Posted at 2023-05-29

ReactのUIフレームワークであるMUI(Material UI)のAutocompleteコンポーネントで下記のエラーが出る場合の対処法です。

Autocompleteのエラー内容

Warning: Encountered two children with the same key, ``.
Keys should be unique so that components maintain their identity across updates.
Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.

Autocompleteのoptionsのkeyに同一のものがあると言うエラーです。

コードは下記になります。

const Home = () => {
  const [value, setValue] = useState()
  const options = [
    { id: 1, name: 'Ken', role: 0, age: 35 },
    { id: 2, name: 'Taro', role: 1, age: 42 },
    { id: 3, name: 'Tom', role: 2, age: 45 }
  ]
  return (
    <Container>
      <Autocomplete
        options={options}
        isOptionEqualToValue={(option, v) => option.id === v.id}
        getOptionLabel={(option) => option.name}
        onChange={(_e, item) => {
          return setValue(item)
        }}
        value={value || null}
        noOptionsText="見つかりません"
        renderInput={(params) => <TextField {...params} fullWidth />}
      />
    </Container>
  )
}

export default Home

renderOptionにkeyを割り当てることで解決

AutocompleteコンポーネントのrenderOptionにkeyを割り当てることで解決しました。

renderOption={(props, option) => {
  return (
    <Box component="li" {...props} key={option.id}>
      {option.name}
    </Box>
  )
}}

{...props} key={option.id}のようにpropsを先に記述する必要がありました。

全体のコード

import { Autocomplete, Box, Container, TextField } from '@mui/material'
import { useState } from 'react'

const Home = () => {
  const [value, setValue] = useState()
  const options = [
    { id: 1, name: 'Ken', role: 0, age: 35 },
    { id: 2, name: 'Taro', role: 1, age: 42 },
    { id: 3, name: 'Tom', role: 2, age: 45 }
  ]
  return (
    <Container>
      <Autocomplete
        options={options}
        isOptionEqualToValue={(option, v) => option.id === v.id}
        getOptionLabel={(option) => option.name}
        onChange={(_e, item) => {
          return setValue(item)
        }}
        value={value || null}
        noOptionsText="見つかりません"
        renderOption={(props, option) => {
          return (
            <Box component="li" {...props} key={option.id}>
              {option.name}
            </Box>
          )
        }}
        renderInput={(params) => <TextField {...params} fullWidth />}
      />
    </Container>
  )
}

export default Home
3
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
3
0