Skip to content

Instantly share code, notes, and snippets.

@pyldin601
Created November 1, 2017 08:16
Show Gist options
  • Save pyldin601/e014156a0e516591109d5f2342505648 to your computer and use it in GitHub Desktop.
Save pyldin601/e014156a0e516591109d5f2342505648 to your computer and use it in GitHub Desktop.
import * as React from 'react';
interface BlurTextInputStateInterface {
value: string,
lastChangeEvent: React.ChangeEvent<HTMLInputElement>,
}
export default class extends React.Component<React.InputHTMLAttributes<HTMLInputElement>, BlurTextInputStateInterface> {
constructor(props: any) {
super(props);
this.state = {
value: props.value,
lastChangeEvent: null,
};
this.onChange = this.onChange.bind(this);
this.onBlur = this.onBlur.bind(this);
}
public componentWillReceiveProps(nextProps) {
if (nextProps.value === this.props.value) {
return;
}
this.setState({
value: nextProps.value,
lastChangeEvent: null,
})
}
public onBlur() {
if (this.state.lastChangeEvent) {
this.props.onChange(this.state.lastChangeEvent);
}
}
public onChange(event: React.ChangeEvent<HTMLInputElement>) {
event.persist();
this.setState({
value: event.currentTarget.value,
lastChangeEvent: event,
});
}
public render() {
return <input
{...this.props}
onBlur={this.onBlur}
onChange={this.onChange}
value={this.state.value}
/>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment