I have an input field with a "close (x)" icon next to it. I am handling state as the value in the input field changes, and once the user hits Enter I clear the value in the state. However, after the re-rendering (because of state change) the previous input still remains there in the input field.
constructor(props) {
super(props);
this.state = {
filterSearchQuery: null, filterSearch: null}
this.handleSearchInput = this.handleSearchInput.bind(this);
this.handleSearchReset = this.handleSearchReset.bind(this);
}
handleSearchInput(e) {
// e.preventDefault();
let val = e.target.value;
if (e.keyCode == 13)
this.setState({ entries: [], filterSearchQuery: null, filterSearch: val, pageIndex: 0, hasMore: false }, this.loadEntries);
else
this.setState({ filterSearchQuery: val });
}
handleSearchReset(e) {
//e.preventDefault();
this.setState({ entries: [], pageIndex: 0, hasMore: false, filterSearchQuery: null, filterSearch: null }, this.loadEntries);
}
render and return :
<input type="text" className="outline-none flex-fill pt-0_2em pb-0_2em border-white border-none bg-color-white color-black font-12px font-weight-bold opacity-0_9" value={this.state.filterSearchQuery} placeholder="Search in results." onKeyUp={(e) => this.handleSearchInput(e)} onChange={(e) => this.handleSearchInput(e)} autoFocus={true} />
{
(this.state.filterSearchQuery && this.state.filterSearchQuery.length > 0) &&
<div className="">
<button type="button" className="close" aria-label="Close" onClick={this.handleSearchReset}>
<span aria-hidden="true">×</span>
</button>
</div>
}
The handleSearchReset
function works and sets the state as expected. Both the filterSearch
and filterSearchQuery
values are set properly. However, after re-rendering the filterSearchQuery
value still is visible in the input field. How can I overcome this or where am I missing?