Skip to content

Instantly share code, notes, and snippets.

@ArtemVeremienko
Created October 8, 2020 16:49
Show Gist options
  • Save ArtemVeremienko/6e37757e541ea410b533ffece8abd316 to your computer and use it in GitHub Desktop.
Save ArtemVeremienko/6e37757e541ea410b533ffece8abd316 to your computer and use it in GitHub Desktop.
Lazy input
import React from 'react';
import PropTypes from 'prop-types';
export default class extends React.Component {
static defaultProps = {
onChange: function (e) { },
nativeProps: {}
}
static propTypes = {
value: PropTypes.any.isRequired,
onChange: PropTypes.func,
nativeProps: PropTypes.object
}
nativeInput = React.createRef();
componentDidUpdate(prevProps, prevState) {
let inp = this.nativeInput.current;
if (prevProps.value !== this.props.value ||
this.props.value != inp.value
) {
inp.value = this.props.value;
}
}
checkChange = (e) => {
if (this.props.value.toString() !== e.target.value) {
this.props.onChange(e);
}
}
checkEnterKey = (e) => {
if (e.keyCode === 13) {
this.checkChange(e);
}
}
render() {
return (
<input {...this.props.nativeProps}
defaultValue={this.props.value}
onBlur={this.checkChange}
onKeyUp={this.checkEnterKey}
ref={this.nativeInput}
/>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment