How to add Light Snack bar to NextJs App
I have seen many modules which can be used as snack-bar but i want to keep my code light and the snack-bar fully customisable. So let’s see how i added snackbar to my recent next-js web app
Step 1: First Add
function MyApp({ Component, pageProps }) {
return <>
<Component {...pageProps} /> <div id="blurweb__snackbar"></div>
</>
}
Now once you have added this not this snackbar can be used from any page of your nextjs app
Step 2: Add showSnackbar function, just create a file called utils.js and add this so we can import it to any page when required.
export function showSnackbar(message) {
// Get the snackbar DIV
var x = document.getElementById("blurweb__snackbar");
// Add the "show" class to DIV
x.innerText = `${message}`;
x.className = "show";
// After 3 seconds, remove the show class from DIV
setTimeout(function () {
x.className = x.className.replace("show", "");
}, 3000);
}
Step 3: Add the styling
``` #blurweb__snackbar { visibility: hidden; / Hidden by default. Visible on click / width: 50vw; min-width: 250px; / Set a default minimum width / margin-left: -25vw; / Divide value of min-width by 2 / background-color: #333; / Black background color / color: #fff; / White text color / text-align: center; / Centered text / border-radius: 2px; / Rounded borders / padding: 16px; / Padding / position: fixed; / Sit on top of the screen / z-index: 132535235; / Add a z-index if needed / left: 50%; / Center the snackbar / bottom: 30px; / 30px from the bottom / }
/ Show the snackbar when clicking on a button (class added with JavaScript) /
#blurweb__snackbar.show { visibility: visible; / Show the snackbar / / Add animation: Take 0.5 seconds to fade in and out the snackbar. However, delay the fade out process for 2.5 seconds / / -webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s; / / animation: fadein 0.5s, fadeout 0.5s 2.5s; / }```
I have some css commented and according to me, you can customise this as you like
Done 🎉 to use it just call the showSnackbar(”message”) with your message
thanks for reading if you want to try how this works i have added this to blurweb.app when you will submit email on the page if wrong it will show snackbar
Subscribe to my newsletter
Read articles from Sanskar Tiwari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Sanskar Tiwari
Sanskar Tiwari
Building a portfolio of micro saas apps.