Reputation: 13
I have a search bar using input field which has a onkeyup function
which is working properly. I want to add a option that when someone cilcks some text then the search value with be updated and onkeyup will be called that means i want to add a text on search field and and search on that text. The value is updating
but the onkeyup is not calling
.
class Search extends React.Component {
constructor(props) {
super(props)
this.state = {
searchValue : null
}
this.onChange = this.onChange.bind(this)
this.onClickChange = this.onClickChange.bind(this)
}
onChange(e) {
this.setState({
searchValue: e.target.value
})
}
onClickChange(e) {
this.setState({
searchValue: e.target.innerText
});
}
search() {
// working function no need to modify
}
render() {
<input type="text" id="Search" className="form-control" placeholder="Search" onKeyUp={() => this.search()} onChange={this.onChange} value={this.state.searchValue}/>
<span onClick={this.onClickChange}>CUSTOM</span>
}
}
Upvotes: 1
Views: 1577
Reputation: 4974
If you would like to search based on clicked text, you should not expect that onKeyUp
is called, because this event just called when you're writing some text in the input
. It's better to use callback
which exist in setState
in the classify
components. So just call your search method in the call back of onClickChange
when you clicked the text. You can use this way same as bellow:
onClickChange(e) {
this.setState({
searchValue: e.target.innerText
},()=>{
this.search();
});
}
Upvotes: 3
Reputation: 498
I believe your problem is that you are expecting onKeyUp
to be called automatically when onClickChange
is activated. Normally it shouldn't, as they aren't related events. If you want search to be performed onClickChange
, then specify this in the body of onClickChange
function:
onClickChange(e) {
this.setState({
searchValue: e.target.innerText,
});
this.search(e.target.innerText); // sending searchValue as parameter to search function
}
I deliberately sent e.target.innerText
(the searchValue) as a parameter to the search
function, since this.setState
is not synchronous, and will probably finish executing after search
has been called. I believe you are using this.state.searchValue
on your search
function. You will need to modify your search function to get the value directly when called:
search(searchValue) {
// use searchValue here
...
}
No need for onKeyUp
on your input, just modify onChange
like this:
<input type="text" id="Search" className="form-control" placeholder="Search" onChange={(e) => this.onChange(e.target.value)} value={this.state.searchValue} />
and implement it like this:
onChange(searchValue) {
this.setState({ searchValue })
this.search(searchValue);
}
This is just one approach, if this doesn't work for your requirements, then please say so and I will edit my answer.
Upvotes: 1