Play a Sound When a Notification Arrives

Quickstart

You might want to play a sound or show toast when a new notification arrives. To accomplish this, you can define a function and pass it to your MagicBell component as the onNewNotification property.

React
import React from 'react';
import MagicBell, { FloatingNotificationInbox } from '@magicbell/magicbell-react';

export default function Notifications() {
  const playSound = () => {
    const audio = new Audio(url);
    audio.addEventListener('canplaythrough', (event) => {
      // the audio is now playable; play it if permissions allow
      audio.play();
    });
  };

  return (
    
      {(props) => }
    
  );
}

Using hooks

MagicBell also provides a hook called useMagicBellEvent which can help you to accomplish that. This hook expects a callback function. Play your audio inside that function:

import { useMagicBellEvent } from '@magicbell/magicbell-react';

useMagicBellEvent('notifications.new', (notification) => {
  if (!notification.isSeen) {
    const audio = new Audio(url);
    audio.addEventListener('canplaythrough', (event) => {
      // the audio is now playable; play it if permissions allow
      audio.play();
    });
  }
});

The only requirement to use that hook is that the component you use is wrapped with the MagicBellProvider.

Wrapping your app with the MagicBell provider

Since this is a headless component, it is safe to wrap your app with the MagicBellProvider.

import React from 'react';
import MagicBell, {
  MagicBellProvider,
  FloatingNotificationInbox,
} from '@magicbell/magicbell-react';

function App() {
  return (
    
      
      
      
    
  );
}

function Notifications() {
  useMagicBellEvent('notifications.new', (notification) => {
    alert(notification.title);
  });

  return (
    
      {(props) => }
    
  );
}

Notice that the Notifications component is part of the component tree where the MagicBellProvider is available. That's why it is possible to add the useMagicBellEvent hook in that component.