Skip to content

Instantly share code, notes, and snippets.

@arqex
Last active September 18, 2021 09:18
Show Gist options
  • Save arqex/b90c1dee5f35656cd0dd to your computer and use it in GitHub Desktop.
Save arqex/b90c1dee5f35656cd0dd to your computer and use it in GitHub Desktop.
11.toaster.js
/* OUR TOASTER COMPONENT */
// This is our singleton toaster
var singleton;
export default class Toaster extends React.Component {
constructor(){
super();
this.state = {toasts: []};
}
// start the singleton
static start( ref ){
singleton = ref;
}
// A method to show toasts from everywhere
static show( contents ){
singleton.add( contents );
}
// The add method will control how toasts appear and dissapear
add( contents ){
var toasts = this.state.toasts.slice();
toasts.push( contents );
this.setState({toasts: toasts});
// The toast should be gone after n seconds
setTimeout( () => {
var toasts = this.state.toasts.slice();
toasts.unshift();
this.setState({toasts: toasts});
}, n)
}
// more methods....
}
/* ADD THE TOASTER TO THE APP TO USE IT */
class App extends React.Component {
render(){
// Add the toaster to the DOM
return (
<div>
{contents}
<Toaster ref="toaster" />
</div>
);
}
componentDidMount(){
// Start the singleton
Toaster.start( this.refs.toaster );
}
}
/* IN ANY OTHER COMPONENT AT ANY TIME */
import Toaster from 'toaster';
Toaster.show( 'Great! Your toast is hot!' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment