Posts > Simple Notification Component

Simple Notification Component

Let’s create a simple notification component without using any library.

Notification.js

import { useEffect } from 'react';

export default function Notification({message, onClose}){
	useEffect(() => {
    const timer = setTimeout(() => {
      onClose();
    }, 3000); // Hide notification after 3 seconds

    return () => clearTimeout(timer); // Clear the timer if the component unmounts
  }, [onClose]);

  return <div>{ message }</div>;
}

Import Notification.js into your layout.

	import { useState } from 'react';
	
	
	export default function Layout(){
		const [ notification, setNotification ] = useState('')
	
		function hideNotification() {
		    setNotification('');
	  }
	
		return (
			<>
				{notification && (
	        <Notification message={notification} onClose={hideNotification} />
	      )}
				{/* rest of layout codes */}
			</>
		)
	}

So how will we add a message to the notification? And what will trigger it?

Using POST / PUT

try {
  POST(`server api url`, payload, {
    credentials: 'omit',
    headers: HEADERS,
	}).then((result) => {
	  setNotification(result);
	  });
} catch (error) {
  setNotification('Error ', error);
}

{/* or use PUT */}

try {
  PUT(`server api url`, payload, {
    credentials: 'omit',
    headers: HEADERS,
  }).then((result) => {
    setNotification(result);
  });
} catch (error) {
  setNotification('Error ', error);
}

Or anything else you want to use as long it got triggered 😅

Tags 🏷