Created
February 11, 2019 11:51
-
-
Save leonid-shevtsov/1378f373145d1c19d7e787d005c8cb37 to your computer and use it in GitHub Desktop.
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
import * as React from 'react'; | |
export type ToggleChildProps = { | |
toggle: () => void; | |
}; | |
type WithToggleChildProps<P extends object> = ToggleChildProps & | |
Pick<P, Exclude<keyof P, 'viewComponent' | 'editComponent'>>; | |
type ToggleProps<P extends object> = { | |
viewComponent: React.ComponentType<WithToggleChildProps<P>>; | |
editComponent: React.ComponentType<WithToggleChildProps<P>>; | |
} & P; | |
type ToggleState = { | |
editing: boolean; | |
}; | |
class Toggle<P extends object> extends React.Component<ToggleProps<P>, ToggleState> { | |
constructor(props: ToggleProps<P>) { | |
super(props); | |
this.toggle = this.toggle.bind(this); | |
this.state = { editing: false }; | |
} | |
toggle() { | |
const { editing } = this.state; | |
this.setState({ editing: !editing }); | |
} | |
render() { | |
const { editing } = this.state; | |
const { viewComponent: ViewComponent, editComponent: EditComponent, ...props } = this | |
.props as ToggleProps<P>; | |
return editing ? ( | |
<EditComponent toggle={this.toggle} {...props} /> | |
) : ( | |
<ViewComponent toggle={this.toggle} {...props} /> | |
); | |
} | |
} | |
export default Toggle; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment