Skip to content

Instantly share code, notes, and snippets.

@iamdanthedev
Created January 26, 2018 00:03
Show Gist options
  • Save iamdanthedev/9760099a2b72d203c3cdeb6240e0504e to your computer and use it in GitHub Desktop.
Save iamdanthedev/9760099a2b72d203c3cdeb6240e0504e to your computer and use it in GitHub Desktop.
withConfirm react hoc
import * as React from 'react';
import { compose, withStateHandlers } from 'recompose';
import Confirm from 'semantic-ui-react/dist/commonjs/addons/Confirm/Confirm';
/**
* with confirm hoc
* wraps an underlying component with a modal action confirmation
*/
export type ConfirmOptions = {
confirmText?: string; // text to display when confirm is triggered
onConfirm?: () => any; // action if confirmed
};
type State = { isConfirmVisible: boolean };
type Updaters = {
showConfirm: () => any;
hideConfirm: () => any;
};
type WrappedProps = State & Updaters & ConfirmOptions;
export const WithConfirm = compose<WrappedProps, ConfirmOptions>(
withStateHandlers<State, Updaters, WrappedProps>(
{ isConfirmVisible: false },
{
showConfirm: ({ isConfirmVisible }) => () => ({
isConfirmVisible: true,
}),
hideConfirm: ({ isConfirmVisible }) => () => ({
isConfirmVisible: false,
}),
},
),
)(props => {
const {
children,
confirmText,
onConfirm,
showConfirm,
hideConfirm,
isConfirmVisible,
} = props;
const child = React.Children.only(props.children);
const cloned = React.cloneElement(child, { onClick: showConfirm });
return (
<>
<Confirm
open={isConfirmVisible}
onCancel={hideConfirm}
onConfirm={() => {
hideConfirm();
typeof onConfirm === 'function' && onConfirm();
}}
/>
{cloned}
</>
);
});
export default WithConfirm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment