Last active
December 20, 2016 16:26
-
-
Save leMaik/7e6a9ab239ec620b04998392715ef212 to your computer and use it in GitHub Desktop.
A convenient way to use Material-UI's Snackbar.
This file contains 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 React from 'react' | |
import { render } from 'react-dom' | |
import SnackbarProvider from './SnackbarProvider' | |
export class DemoComponent extends React.Component { | |
render () { | |
return ( | |
<button onClick={() => this.context.snackbar.showMessage('Hello world')}>Click me</button> | |
) | |
} | |
} | |
DemoComponent.contextTypes = { | |
snackbar: PropTypes.shape({ | |
showMessage: PropTypes.func | |
}) | |
} | |
render((<SnackbarProvider><DemoComponent /></SnackbarProvider>), document.getElementById('react-target')) |
This file contains 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 React, { Component, PropTypes } from 'react' | |
import Snackbar from 'material-ui/Snackbar' | |
export default class SnackbarProvider extends Component { | |
constructor (props) { | |
super(props) | |
this.state = { | |
message: null, | |
open: false | |
} | |
} | |
getChildContext () { | |
return { | |
snackbar: { | |
showMessage: this.showMessage.bind(this) | |
} | |
} | |
} | |
showMessage (message, action, handleAction) { | |
this.setState({ open: true, message, action, handleAction }) | |
} | |
handleActionTouchTap () { | |
this.handleRequestClose() | |
this.state.handleAction() | |
} | |
handleRequestClose () { | |
this.setState({ open: false, message: null, action: null, handleAction: null }) | |
} | |
render () { | |
return ( | |
<div style={{ width: 'inherit', height: 'inherit' }}> | |
{this.props.children} | |
<Snackbar | |
open={this.state.open} | |
message={this.state.message} | |
action={this.state.action} | |
autoHideDuration={4000} | |
onActionTouchTap={() => this.handleActionTouchTap()} | |
onRequestClose={() => this.handleRequestClose()} | |
/> | |
</div> | |
) | |
} | |
} | |
SnackbarProvider.childContextTypes = { | |
snackbar: PropTypes.shape({ | |
showMessage: PropTypes.func | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment