Skip to content

Instantly share code, notes, and snippets.

@srph
Last active June 13, 2017 06:22
Show Gist options
  • Select an option

  • Save srph/2901195d99468185dc79f1ec10fc8eb4 to your computer and use it in GitHub Desktop.

Select an option

Save srph/2901195d99468185dc79f1ec10fc8eb4 to your computer and use it in GitHub Desktop.
React: Example SearchInput

SearchInput

Input that automatically sets the search query parameter to the input. Also, input value defaults to the current search query parameter.

Usage

<SearchInput />
import React, {Component, PropTypes as T} from 'react';
import history from 'app/history';
class SearchInput extends Component {
constructor(props, context) {
super(props);
this.state = {
input: context.location.query.search || ''
}
this.timeout = null;
this.handleChange = this.handleChange.bind(this);
}
render() {
return (
<input type="text"
className="form-input"
value={this.state.input}
onChange={this.handleChange}
placeholder="Search for customer by name..." />
);
}
handleChange(evt) {
clearTimeout(this.timeout);
if (this.state.input === evt.target.value) {
return;
}
this.setState({
input: evt.target.value
});
this.timeout = setTimeout(() => {
history.push(`${this.context.location.pathname}?search=${this.state.input}`);
}, 500);
}
}
SearchInput.contextTypes = {
location: T.object
}
export default SearchInput;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment