Created
November 2, 2021 18:22
-
-
Save mauriciord/c54f8701132dba12cd70b5f2ebc24f2e to your computer and use it in GitHub Desktop.
Snackbar component
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 React, { createContext, useContext, useState, useEffect } from "react"; | |
const SnackbarContext = createContext(); | |
const Provider = ({ children }) => { | |
const [state, setState] = useState([]); | |
console.log(state); | |
return ( | |
<SnackbarContext.Provider value={{ state, setState }}> | |
{children} | |
</SnackbarContext.Provider> | |
); | |
}; | |
// if ID is necessary, it can be assumed "message" will be unique, or shortid.generate() can be used | |
export function Snackbar({ message, duration = 3000 }) { | |
const { state, setState } = useContext(SnackbarContext); | |
useEffect(() => { | |
setState((prevState) => [...prevState, message]); | |
}, [message, setState]); | |
useEffect(() => { | |
if (state[0] === message) { | |
const timeoutId = setTimeout( | |
() => setState((prevState) => prevState.filter((id) => id !== message)), | |
duration | |
); | |
return () => { | |
clearTimeout(timeoutId); | |
}; | |
} | |
}, [duration, message, setState, state]); | |
return state[0] === message ? ( | |
<div className="snackbar"> | |
<p>{message}</p> | |
</div> | |
) : null; | |
} | |
export const App = () => { | |
return ( | |
<Provider> | |
<Snackbar message="First" /> | |
<Snackbar message="Second" duration={5000} /> | |
<Snackbar message="Third" /> | |
</Provider> | |
); | |
}; | |
// First is displayed | |
// After 3 seconds, "First" disappears and "Second" is displayed | |
// After 5 seconds, "Second" disappears and "Third" is displayed | |
// After 3 seconds, no messages are displayed anymore |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment