How to get selected value of mui autocomplete in react js?
January 13, 2023Hi Friends 👋,
Welcome To aGuideHub!
To get selected value of mui autocomplete in React js, you can use mui autocomplete onchange
attribute, in the onchange
attribute, you have to set their value in your state. It will get the selected value of mui autocomplete.
Today, I am going to show you, how to get selected value of mui autocomplete in react js.
Installation
Install the following packages to use get selected value of mui autocomplete in react js.
npm
npm install @mui/material @emotion/react @emotion/styled
yarn
yarn add @mui/material @emotion/react @emotion/styled
MUI material get selected value of mui autocomplete example.
The below code is an example of a Material UI autocomplete get selected value. You have to import @mui material
autocomplete and you can use mui autocomplete value={value}
attribute, in the onchange
attribute, you have to set their value in your state.
App.js
import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
const options = ['Option 1', 'Option 2'];
export default function ControllableStates() {
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={(event, newValue) => {
setValue(newValue);
}}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
id="controllable-states-demo"
options={options}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Controllable" />}
/>
</div>
);
}
In the above code example, I have used the @mui/material
component and get selected value of mui autocomplete in react js.
Check the output of the above code example.
All the best 👍