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 (
    <MagicBell
      apiKey="MAGICBELL_API_KEY"
      userEmail="mary@example.com"
      onNewNotification={playSound}
    >
      {(props) => <FloatingNotificationInbox height={500} {...props} />}
    </MagicBell>
  );
}

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 (
    <MagicBellProvider apiKey="MAGICBELL_API_KEY" userExternalId="u001">
      <Notifications />
      <MainMenu />
      <Content />
    </MagicBellProvider>
  );
}

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

  return (
    <MagicBell>
      {(props) => <FloatingNotificationInbox height={500} {...props} />}
    </MagicBell>
  );
}

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.