Skip to content

Instantly share code, notes, and snippets.

@rodrigonehring
Created October 26, 2018 16:52
Show Gist options
  • Save rodrigonehring/579a89249277243241d293395a9a073d to your computer and use it in GitHub Desktop.
Save rodrigonehring/579a89249277243241d293395a9a073d to your computer and use it in GitHub Desktop.
Snackbar to react 16.7 hooks (material-ui)
import React, { createContext, useState } from 'react'
import Snackbar from '@material-ui/core/Snackbar'
import Button from '@material-ui/core/Button'
import IconButton from '@material-ui/core/IconButton'
const Context = createContext()
function RenderSnack({ id, message, open, handleClose }) {
const messageId = `message-${id}`
return (
<Snackbar
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left',
}}
open={open}
autoHideDuration={6000}
onClose={handleClose}
ContentProps={{
'aria-describedby': messageId,
}}
message={<span id={messageId}>{message}</span>}
action={[
<Button key="undo" color="secondary" size="small" onClick={handleClose}>
UNDO
</Button>,
<IconButton key="close" aria-label="Close" color="inherit" onClick={handleClose}>
X
</IconButton>,
]}
/>
)
}
let uniqueId = 2
export const SnackProvider = ({ children }) => {
const [{ current, queue }, setState] = useState({ current: null, queue: [] })
function createSnack(message, options) {
const id = uniqueId++
const snack = { id, message, open: true, options }
if (current) {
setState({ current, queue: queue.concat(snack) })
} else {
setState({ queue, current: snack })
}
return id
}
function handleClose() {
setState((currentState) => ({
...currentState,
current: { ...currentState.current, open: false },
}))
// time to snack close animation
setTimeout(openNext, 1000)
}
function openNext() {
if (queue.length) {
setState({ current: queue[0], queue: queue.slice(1) })
} else {
setState({ current: null, queue: [] })
}
}
return (
<Context.Provider value={{ createSnack }}>
{current && <RenderSnack key={current.id} {...current} handleClose={handleClose} />}
{children}
</Context.Provider>
)
}
export default Context
@odysseymemoirs
Copy link

thanks, this is exactly what i needed

@bertdida
Copy link

Thanks, I suggest to pass openNext as onExited prop to Snackbar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment