I need to perform a Search when user stops typing.I know I am supposed to use setTimeout() . But with Reactjs I cant find how it works. Can someone please tell me how to invoke a method (that will handle Search) when the user stops typing for a few seconds (suppose 5).I cant figure out where to write the code to check that the user has stopped typing.
import React, {Component, PropTypes} from 'react'; export default class SearchBox extends Component { state={ name:" ", } changeName = (event) => { this.setState({name: event.target.value}); } sendToParent = () => { this.props.searching(this.state.name); } render() { return ( <div> <input type="text" placeholder='Enter name you wish to Search.' onChange={this.changeName} /> </div> ); } }
I want to invoke the sendToParent method when the user stops typing.
Executing a function after a certain amount of inactivity is known as debouncing. Debouncing can be helpful for many reasons. One of the most popular applications in web development is to execute a search or filter some results after a user has stopped typing text in a textbox.
How to use setTimeout in React. The setTimeout function accepts two arguments: the first is the callback function that we want to execute, and the second specifies the timeout in milliseconds before the function will be called. setTimeout(() => console. log('Initial timeout!'
What is onBlur event in React. React onBlur behaves just like the native JavaScript version of blur. Every time you get out of focus from the input field, the event will trigger. It doesn't matter if the value has changed or not, every time you get out of focus.
You can use setTimeout
with respect to your code as follows,
state = { name: '', typing: false, typingTimeout: 0 } changeName = (event) => { const self = this; if (self.state.typingTimeout) { clearTimeout(self.state.typingTimeout); } self.setState({ name: event.target.value, typing: false, typingTimeout: setTimeout(function () { self.sendToParent(self.state.name); }, 5000) }); }
Also, you need to bind changeName
handler function in constructor.
constructor(props) { super(props); this.changeName = this.changeName.bind(this); }
Implement using useEffect hook:
function Search() { const [searchTerm, setSearchTerm] = useState('') useEffect(() => { const delayDebounceFn = setTimeout(() => { console.log(searchTerm) // Send Axios request here }, 3000) return () => clearTimeout(delayDebounceFn) }, [searchTerm]) return ( <input autoFocus type='text' autoComplete='off' className='live-search-field' placeholder='Search here...' onChange={(e) => setSearchTerm(e.target.value)} /> ) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With