Created
March 30, 2017 09:14
-
-
Save jakobz/bc54a6d9558ef07bf69b2eebf209d143 to your computer and use it in GitHub Desktop.
Simple Lenses for React props
This file contains hidden or 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
| interface LensProps<T> { | |
| value: T, | |
| onValueChange(newValue: T): void; | |
| } | |
| function propLens<TParent extends object, Name extends keyof TParent>(parent: LensProps<TParent>, name: Name): LensProps<TParent[Name]> { | |
| return { | |
| value: parent.value[name], | |
| onValueChange: (newValue) => parent.onValueChange({ ...parent.value as any, [name as any]: newValue }) | |
| } | |
| } | |
| interface State { | |
| table1: TableState, | |
| table2: TableState | |
| } | |
| export class Viewer extends React.Component<any, any> { | |
| state: State = { | |
| table1: {}, | |
| table2: {} | |
| }; | |
| render() { | |
| let stateLens: LensProps<State> = { | |
| value: this.state, | |
| onValueChange: (newValue) => this.setState(newValue) | |
| } | |
| return dom.div({}, | |
| dom.div({}, table({ name: "Table 1", ...propLens(stateLens, 'table1') })), | |
| dom.div({}, table({ name: "Table 2", ...propLens(stateLens, 'table2') })) | |
| ) | |
| } | |
| } | |
| export const viewer = React.createFactory(Viewer); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment