Created
October 9, 2019 11:48
-
-
Save cip123/0f63d5d3ec79e53ef50bde82a762f251 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { Component, useState } from "react"; | |
| import TextField from "@material-ui/core/TextField"; | |
| const WAIT_INTERVAL = 1000; | |
| const ENTER_KEY = 13; | |
| class TextSearch extends Component { | |
| state = { | |
| value: "", | |
| isTyping: false | |
| }; | |
| timer = null; | |
| static getDerivedStateFromProps(nextProps, prevState) { | |
| // we watch the value from the props to catch the reset event | |
| if (!prevState.isTyping && nextProps.filterValue === "") { | |
| return { | |
| value: "" | |
| }; | |
| } | |
| return null; | |
| } | |
| handleChange = e => { | |
| clearTimeout(this.timer); | |
| this.setState({ value: e.target.value, isTyping: true }); | |
| this.timer = setTimeout(this.triggerChange, WAIT_INTERVAL); | |
| }; | |
| handleKeyDown = e => { | |
| if (e.keyCode === ENTER_KEY) { | |
| clearTimeout(this.timer); | |
| this.triggerChange(); | |
| } | |
| }; | |
| triggerChange = () => { | |
| const { value } = this.state; | |
| this.props.onChange(value); | |
| this.setState({ isTyping: false }); | |
| }; | |
| render() { | |
| const { ...rest } = this.props; | |
| return ( | |
| <TextField | |
| type={rest.type} | |
| fullWidth | |
| label={rest.label} | |
| value={this.state.value} | |
| placeholder={rest.placeholder} | |
| onKeyDown={this.handleKeyDown} | |
| onChange={this.handleChange} | |
| /> | |
| ); | |
| } | |
| } | |
| export default TextSearch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment