Reputation: 313
I want to show an alert message in ReactJS when the user stops typing in a a form field.
Upvotes: 1
Views: 4860
Reputation: 582
Here, I created React functional component for my use.
const App = () => {
let typingTimer = null;
const makeAnApiCall =(inputValue) => {
console.log("Making an Ajax Call");
window.alert('Making an Ajax Call');
}
const handleChange = (evt) => {
const val = evt.target.value;
clearTimeout(typingTimer);
typingTimer = setTimeout(() => {
if (val) {
makeAnApiCall(val)
}
}, 500);
}
useEffect(() => {
return () => {
clearTimeout(typingTimer);
}
}, [])
return (
<div>
<input type="text" onChange={handleChange} />
</div>
);
}
Workgin demo on stackblitz
Upvotes: 2
Reputation: 1533
This can help you.
This kind of features are not React specific, so you can achieve that in many ways with JS.
Simple component :
class App extends Component {
typingTimer = null;
handleChange = (evt) => {
const val = evt.target.value;
clearTimeout(this.typingTimer);
this.typingTimer = setTimeout(() => {
if (val) {
window.alert('Stopped typing !');
}
}, 500);
}
componentWillUnmount() {
clearTimeout(this.typingTimer);
}
render() {
return (
<div>
<input onChange={this.handleChange} />
</div>
);
}
}
Upvotes: 6