A component is changing an uncontrolled Autocomplete to be controlled

You ensured that the value property never had been undefined, but you had to do same for inputValue.

  1. the “value” state with the value/onChange props combination. This state represents the value selected by the user, for instance when pressing Enter.
  2. the “input value” state with the inputValue/onInputChange props combination. This state represents the value displayed in the textbox.

⚠️ These two state are isolated, they should be controlled independently.

Component becomes uncontrolled when inputValue property is undefined, and vice versa.

If in the following example you delete an empty string from
React.useState('') you’ll get the same error message because inputValue during first render is undefined.

import React from 'react'
import TextField from '@material-ui/core/TextField'
import Autocomplete from '@material-ui/lab/Autocomplete'

const options = ['Option 1', 'Option 2']

export default function AutocompleteLab() {
  const [value, setValue] = React.useState(options[0])
  const [inputValue, setInputValue] = React.useState('')

  return (
    <div>
      <div>{`value: ${value !== null ? `'${value}'` : 'null'}`}</div>
      <div>{`inputValue: '${inputValue}'`}</div>
      <br />
      <Autocomplete
        value={value}
        onChange={(_, newValue) => {
          setValue(newValue)
        }}
        inputValue={inputValue}
        onInputChange={(_, newInputValue) => {
          setInputValue(newInputValue)
        }}
        options={options}
        style={{ width: 300 }}
        renderInput={(params) => <TextField {...params} label="Name" variant="outlined" />}
      />
    </div>
  )
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)