nikUnique
Published on

Adding Desktop Notifications to a React App

Authors
  • avatar
    Name
    nikUnique
    Twitter

Here is how you can add desktop notifications to your React app.

Step 1: Requesting Permission

The first step in implementing desktop notifications is to request permission from the user. Browsers require explicit permission to show notifications, so it is essential to handle this gracefully.

Here is a function to request notification permission:

function requestNotificationPermission () {
  if (Notification.permission === 'granted') {
    console.log('Permission already granted')
  } else if (Notification.permission !== 'denied') {
    Notification.requestPermission().then((permission) => {
      if (permission === 'granted') {
        console.log('Permission granted')
      }
    })
  }
}

Step 2: Creating the Notification Function

Also, create a function to trigger notifications. This function takes a title and an object of options as parameters:

function showNotification(title, options) {
  if (Notification.permission === "granted") {
    new Notification(title, options);
  }
}

To learn more about the Notification API, visit the MDN documentation.

Step 3: Bringing It All Together

Now, it is time to integrate our functions into a React component. I've also created a simple wrapper function around the showNotification function call, and I added some JSX that includes two buttons: one for requesting permission because the permission should be requested from the user action, and another for sending the notification itself. So, the result is below:

function App() {
  function requestNotificationPermission() {
    if (Notification.permission === "granted") {
      console.log("Permission already granted");
    } else if (Notification.permission !== "denied") {
      Notification.requestPermission().then((permission) => {
        if (permission === "granted") {
          console.log("Permission granted");
        }
      });
    }
  }

  function showNotification(title, options) {
    if (Notification.permission === "granted") {
      new Notification(title, options);
    }
  }

  function handleClick() {
    showNotification("New Blog Post!", {
      body: "Check out latest article!",
      icon: "path/to/icon.png", // Optional: path to an icon
    });
  }

  return (
    <div>
      <h1>Welcome to My Blog</h1>
      <button onClick={requestNotificationPermission}>
        Request Permission
      </button>
      <button onClick={handleClick}>Notify Me</button>
    </div>
  );
}

export default App;

If you try to request permission programmatically, then there will be an error that says that the permission can be requested only from the user-generated event (like button click), so you cannot just do it in the useEffect hook.

So, here you go, this is how you can integrate desktop notifications into your React application 🙂.