Reputation: 1215
I'm using Material UI in a Reactjs/Typescript project where I render a search input component using TextField.
The "x" icon is built into the component and clears the value on the input. However, I would like to create my own custom handler to make an api call when the search value is deleted.
I looked at the component and component API docs but haven't come across anything useful. There was another answer that used the browser api to grab the x element and add an event listener, but I would like to avoid directly manipulating the DOM if possible.
<TextField
id="outlined-search"
label="Search users"
type="search"
variant="outlined"
style={{ width: '40ch' }}
value={searchValue}
inputRef={textRef}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => event.target.value !== " " &&
setSearchValue(event.target.value)}
onKeyPress={() => {}}
/>
Upvotes: 0
Views: 1611
Reputation: 547
I think something like below might help. It will call a business logic/API function when input is empty.
const handleChange = async (event) => {
setSearchValue(event.target.value)
// API calls here
if(!event.target.value) {
const response = await api.get();
}
}
<TextField
id="outlined-search"
label="Search users"
type="search"
variant="outlined"
style={{ width: '40ch' }}
value={searchValue}
inputRef={textRef}
onChange={handleChange}
/>
Upvotes: 1