Programmatically set value in material-ui Autocomplete TextField
If you're here trying to test a change handler that is called from MUI's Autocomplete
component:
In your setupTests.js file
import '@testing-library/jest-dom/extend-expect'
document.createRange = () => ({
setStart: () => {},
setEnd: () => {},
commonAncestorContainer: {
nodeName: 'BODY',
ownerDocument: document
}
})
In your test file:
import { render, fireEvent } from '@testing-library/react'
...
const { getByRole } = render(<MyComponentWithAutocomplete />)
const autocomplete = getByRole('textbox')
// click into the component
autocomplete.focus()
// type "a"
fireEvent.change(document.activeElement, { target: { value: 'a' } })
// arrow down to first option
fireEvent.keyDown(document.activeElement, { key: 'ArrowDown' })
// select element
fireEvent.keyDown(document.activeElement, { key: 'Enter' })
expect(autocomplete.value).toEqual('Arkansas')
expect(someChangeHandler).toHaveBeenCalledTimes(1)
For more examples, check out the tests in the library
if you want to show the default selected value in input you must also set inputValue property and onInputChange event of the Autocompelete component
changes in state:
const [value, setValue] = useState("");
const [inputValue, setInputValue] = useState("");
changes in handle click
const handleClick = () => {
setValue(top100Films[0]);
setInputValue(top100Films[0]);
};
changes in autocompelete
<Autocomplete
{...custom}
value={value}
inputValue={inputValue}
onChange={(event, newValue) => {
setValue(newValue);
}}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
options={top100Films}
getOptionLabel={option => option.title}
renderInput={(params) => (
<TextField
{...input}
{...params}
variant="outlined"
/>
)}
/>
you can store desired value in state and pass it to auto complete component.
Import useState:
import React, { useState } from 'react';
using useState:
const [val,setVal]=useState({})
changin value on click of button
const handleClick = () => {
setVal(top100Films[0]);//you pass any value from the array of top100Films
// set value in TextField from dropdown list
};
and pass this value to component in render
<Autocomplete
value={val}
options={top100Films}
getOptionLabel={option => option.title}
style={{ width: 300 }}
renderInput={params => (
<TextField
{...params}
label="Combo box"
variant="outlined"
fullWidth
/>
)}
/>