-
-
Save MegaBlackLabel/aab44c13a222c6ad7a83efa1e5bfe8f9 to your computer and use it in GitHub Desktop.
Recompose withStateHandlers with TypeScript
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'; | |
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