Skip to content

Instantly share code, notes, and snippets.

@jakobz
Created March 30, 2017 09:14
Show Gist options
  • Select an option

  • Save jakobz/bc54a6d9558ef07bf69b2eebf209d143 to your computer and use it in GitHub Desktop.

Select an option

Save jakobz/bc54a6d9558ef07bf69b2eebf209d143 to your computer and use it in GitHub Desktop.
Simple Lenses for React props
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