Using Material-UI’s Autocomplete component with Formik

Your problem is that handleChange won’t work the way you are doing.

If you take a look at the handleChange docs:

General input change event handler. This will update the values[key] where key is the event-emitting input’s name attribute. If the name attribute is not present, handleChange will look for an input’s id attribute. Note: “input” here means all HTML inputs.

Which should work fine, but the problem is that the TextField inside Autocomplete will only trigger handleChange when you type something on it, and the value will be the text, not the id or other property you want, so you need to move handleChange to the Autocomplete.

And there is another problem, you can’t use handleChange in the Autocomplete because it doesn’t references the input you want and it also have different parameters from the normal onChange of the input, as you can see in the docs.

onChange
func
Callback fired when the value changes.
Signature:
function(event: object, value: any) => void
event: The event source of the callback
value: null

So what you need to do is use setFieldValue and pass it to Autocomplete like

onChange={(e, value) => setFieldValue("city_id", value)}

You need to pass the name of your field and what value you want to get.

Here is a working example

Leave a Comment

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