Last active
May 14, 2020 22:17
-
-
Save mrjacobbloom/7e8ee12f5cffb103e732bbcb876cbd97 to your computer and use it in GitHub Desktop.
TypeScript curried onChange handler for 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
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