Last active
January 4, 2021 02:35
-
-
Save rchanou/0a5c4173803a0d654f4c986d696a5c7f to your computer and use it in GitHub Desktop.
Semi-Controlled Input
This file contains 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
export default class Input extends React.Component { | |
static defaultProps = { | |
onChange() {}, | |
onFocus() {}, | |
onBlur() {} | |
}; | |
constructor(props) { | |
super(); | |
this.state = { | |
isFocused: false, | |
currentValue: props.value | |
}; | |
} | |
handleChange = (e, ...rest) => { | |
this.setState({ currentValue: e.target.value }); | |
this.props.onChange(e, ...rest); | |
}; | |
handleFocus = (...args) => { | |
this.setState({ isFocused: true }); | |
this.props.onFocus(...args); | |
}; | |
handleBlur = (...args) => { | |
this.setState({ isFocused: false }); | |
this.props.onBlur(...args); | |
}; | |
componentWillReceiveProps(nextProps) { | |
if (!this.state.isFocused) { | |
this.setState({ currentValue: nextProps.value }); | |
} | |
} | |
render() { | |
return ( | |
<input | |
{...this.props} | |
onChange={this.handleChange} | |
onFocus={this.handleFocus} | |
onBlur={this.handleBlur} | |
value={this.state.currentValue} | |
/> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a very useful little component! Would you mind publishing this on npm (and giving it a license)?