Skip to content

Instantly share code, notes, and snippets.

@krambertech
Created July 2, 2016 10:44
Show Gist options
  • Save krambertech/76afec49d7508e89e028fce14894724c to your computer and use it in GitHub Desktop.
Save krambertech/76afec49d7508e89e028fce14894724c to your computer and use it in GitHub Desktop.
ReactJS: Input fire onChange when user stopped typing (or pressed Enter key)
import React, { Component } from 'react';
import TextField from 'components/base/TextField';
const WAIT_INTERVAL = 1000;
const ENTER_KEY = 13;
export default class TextSearch extends Component {
constructor(props) {
super();
this.state = {
value: props.value
};
}
componentWillMount() {
this.timer = null;
}
handleChange(value) {
clearTimeout(this.timer);
this.setState({ value });
this.timer = setTimeout(::this.triggerChange, WAIT_INTERVAL);
}
handleKeyDown(e) {
if (e.keyCode === ENTER_KEY) {
::this.triggerChange();
}
}
triggerChange() {
const { value } = this.state;
this.props.onChange(value);
}
render() {
const { className } = this.props;
return (
<TextField
className={className}
placeholder={l('Search')}
value={this.state.value}
onChange={::this.handleChange}
onKeyDown={::this.handleKeyDown}
/>
);
}
}
@Soleas93
Copy link

Great share ! Thank you 👍
I did the update told by @barsbek and also added a "searchChanged" boolean so there's no useless API call if the user frantically taps Enter.

    handleChange(e) {
        clearTimeout(this.timerId);
        this.setState({ search: e.target.defaultValue });
        this.searchChanged = true;
        this.timerId = setTimeout(this.updateList, SearchFolder.WAIT_INTERVAL);
    }

    handleKeyDown(e) {
        if (e.keyCode === SearchFolder.ENTER_KEY && this.searchChanged) {
            clearTimeout(this.timerId);
            this.updateList();
        }
    }

    updateList() {
        this.searchChanged = false;
        this.repository.peek(this.state.search, 0, 15, 0).then((response: FolderListItem[]) => {
            this.setState({ listItems: response });
        }).catch((error) => {
            this.setState({ item: "Erreur : " + error.message });
        });
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment