Skip to content

Instantly share code, notes, and snippets.

@MegaBlackLabel
Forked from oukayuka/FlashMessage.tsx
Created February 6, 2018 21:30
Show Gist options
  • Save MegaBlackLabel/aab44c13a222c6ad7a83efa1e5bfe8f9 to your computer and use it in GitHub Desktop.
Save MegaBlackLabel/aab44c13a222c6ad7a83efa1e5bfe8f9 to your computer and use it in GitHub Desktop.
Recompose withStateHandlers with TypeScript
import * as React from 'react';
import { compose, lifecycle, pure, StateHandler, StateHandlerMap, withStateHandlers } from 'recompose';
import { Message, Transition } from 'semantic-ui-react';
import './FlashMessage.css';
export interface FlashMessageProps {
message: string;
isWarning?: boolean;
}
interface StateProps {
visible: boolean;
}
type StateHandlerProps = StateHandlerMap<StateProps> & {
display(): StateHandler<StateProps>;
erase(): StateHandler<StateProps>;
};
type EnhancedFlashMessageProps =
FlashMessageProps &
StateProps &
StateHandlerProps;
const FlashMessage: React.SFC<EnhancedFlashMessageProps> = ({
message = '',
isWarning = false,
visible,
erase,
}) => (
<>
<Transition
visible={visible}
animation="fade"
duration={800}
>
<Message
className="flash-message"
positive={!isWarning}
negative={isWarning}
onDismiss={erase}
>
{message}
</Message>
</Transition>
</>
);
export default compose<
EnhancedFlashMessageProps,
FlashMessageProps
>(
withStateHandlers<
StateProps,
StateHandlerProps,
FlashMessageProps
>(
(props) => ({
...props,
visible: false,
}),
{
display: (state, props) => () => ({
visible: true,
}),
erase: (state, props) => () => ({
visible: false,
}),
},
),
lifecycle<EnhancedFlashMessageProps, {}, {}>({
componentDidMount() {
const { message, display, erase } = this.props;
if (message) {
display();
setTimeout(() => erase(), 3000);
}
},
}),
pure,
)(FlashMessage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment