Skip to content

Instantly share code, notes, and snippets.

@mrjacobbloom
Last active May 14, 2020 22:17
Show Gist options
  • Save mrjacobbloom/7e8ee12f5cffb103e732bbcb876cbd97 to your computer and use it in GitHub Desktop.
Save mrjacobbloom/7e8ee12f5cffb103e732bbcb876cbd97 to your computer and use it in GitHub Desktop.
TypeScript curried onChange handler for controlled input
import * as React from 'react';
import { Form, FormControl } from 'react-bootstrap';
interface IMyComponentState = {
foo: string;
bar: string;
}
export class MyComponent extends React.Component<{}, IMyComponentState> {
public state = {
foo: '',
bar: '',
};
public render(): JSX.Element {
return (
<Form>
<FormControl
onChange={this.onChangeCurry('foo')}
placeholder="Foo"
value={this.state.foo}
/>
<FormControl
onChange={this.onChangeCurry('bar')}
placeholder="Bar"
value={this.state.bar}
/>
</Form>
);
}
@boundMethod
private onChangeCurry(property: keyof IMyComponentState): (event: React.ChangeEvent) => void {
return ({ target: { value } }: React.ChangeEvent<HTMLInputElement>): void => {
this.setState({ [property]: value } as Pick<IMyComponentState, keyof IMyComponentState>);
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment