javascriptreactjsmaterial-uimui-autocomplete

Getting the value in the React Material UI Autocomplete


I am referring to the documentation of React Material-UI (https://material-ui.com/components/autocomplete/).

In the demo code,

    <Autocomplete
      options={top100Films}
      getOptionLabel={(option: FilmOptionType) => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <TextField {...params} label="Combo box" variant="outlined" fullWidth />
      )}
    />

I get how it works, but I am not sure how I am supposed to get the selected value.

For example, I want to use the onChange prop to this so that I can make some actions based on the selection.

I tried adding onChange={v => console.log(v)}

but the v does not show anything related to the selected value.


Solution

  • Solved by using passing in the (event, value) to the onChange props.

    <Autocomplete
        onChange={(event, value) => console.log(value)} // prints the selected value
        renderInput={params => (
            <TextField {...params} label="Label" variant="outlined" fullWidth />
        )}
    />