-2
I have a Material UI autocomplete component, created using the package formik-material-ui
. The component renders an array of model objects below:
const teams = [
{id: 1, name: 'Barcelona'},
{id: 2, name: 'Real Madrid'},
];
When to change the selection (onInputChange
) of Autocomplete
, I need to get only the ID of the selection, what happens is that I’m taking the name.
What would be the correct procedure to get the ID?
import * as React from 'react';
import {render} from 'react-dom';
import {Formik, Form, Field} from 'formik';
import {Button, LinearProgress} from '@material-ui/core';
import MuiTextField from '@material-ui/core/TextField';
import {
Autocomplete,
AutocompleteRenderInputParams,
} from 'formik-material-ui-lab';
import Box from '@material-ui/core/Box';
const teams = [
{id: 1, name: 'Barcelona'},
{id: 2, name: 'Real Madrid'},
];
const App = () => {
const [selected, setSelected] = React.useState('');
const handleShowId = React.useCallback((event, value) => {
alert(value.id);
setSelected(event.target);
}, []);
console.log(selected);
return (
<Formik
initialValues={{
autocomplete: [],
}}
onSubmit={(values, {setSubmitting}) => {
setTimeout(() => {
setSubmitting(false);
alert(JSON.stringify(values, null, 2));
}, 500);
}}
>
{({submitForm, isSubmitting, touched, errors}) => (
<Form>
{isSubmitting && <LinearProgress />}
<Box margin={1}>
<Field
name="autocomplete"
component={Autocomplete}
options={teams}
value={selected}
getOptionLabel={(option: any) => option.name}
style={{width: 300}}
onChange={handleShowId}
renderInput={(params: AutocompleteRenderInputParams) => (
<MuiTextField
{...params}
error={touched['autocomplete'] && !!errors['autocomplete']}
helperText={touched['autocomplete'] && errors['autocomplete']}
label="Autocomplete"
variant="outlined"
/>
)}
/>
</Box>
<Box margin={1}>
<Button
variant="contained"
color="primary"
disabled={isSubmitting}
onClick={submitForm}
>
Submit
</Button>
</Box>
</Form>
)}
</Formik>
);
};
render(<App />, document.getElementById('root'));
https://material-ui.com/pt/components/autocomplete/#controllable-States
– Rafael Tavares
onChange
instead ofonInputChange
returns the selected object– Isac
Right, I had thought about this approach, the problem is that the field is clearing after onChange. I upgraded the SANDBOX.
– Fred