Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.