npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-notification-provider

v0.6.0

Published

Easily create your own notification system in your React app without having to buy into prescribed styling or templating.

Downloads

349

Readme

react-notification-provider

Easily create your own notification system in your React app without having to buy into prescribed styling or templating.

  • 💅 Completely headless. No styling, templates, or HTML included.
  • 🎣 Uses React hooks and context
  • ✨ Easily add animation using Framer Motion.
  • 🏋️‍♀️ Typescript support
  • 📝 Custom notification properties
  • 💻 Mock and test notifications in your app

Here's what it looks like:

function MyComponent() {
  const notification = useNotificationQueue();

  function notify() {
    notification.add('example', {
      title: 'Hello world',
    });
  }

  return <div onClick={notify}>Show notification</div>;
}

Install

With npm:

npm install react-notification-provider

With yarn:

yarn add react-notification-provider

Setup

You'll start by using the createNotificationContext function to create the React context, hooks, and helpers. You should create this in a file you can import throughout your application. In this example, we'll create it as lib/notifications/index.tsx.

import { createNotificationContext } from 'react-notification-provider';

// You can customize the notification interface to include whatever props your notifications need to render.
interface Notification {
  message: string;
  duration: number;
  level: 'success' | 'error';
}

// This function creates a React context and hooks for you so you'll want to export these.
const {
  NotificationProvider,
  useNotificationQueue,
} = createNotificationContext<Notification>();

export { NotificationProvider, useNotificationQueue };

Now you want to wrap your application in this provider. This will allow you to use the useNotificationQueue hooks.

If you're using Next.js you should render this provider in your pages/_app file so that it's available on every page.

import { NotificationProvider } from 'lib/notifications';

function App(props: Props) {
  const { children } = props;

  return (
    <NotificationProvider>
      {children}
      <NotificationList />
    <NotificationProvider>
  );
}

In this example we're rendering a components, NotificationList that will load the notification queue from the React context and render the list of notifications on the page.

In this example, <Notification /> would be your custom component that renders a notification UI component.

import { useNotificationQueue } from 'lib/notifications';

function NotificationList() {
  const queue = useNotificationQueue();

  return (
    <div>
      {queue.entries.map(({ id, data }) => (
        <Notification key={id} message={data.message} />
      ))}
    </div>
  );
}

Now let's add animation to our notifications using Framer motion:

import { useNotificationQueue } from 'lib/notifications';
import { motion, AnimatePresence } from 'framer-motion';

function NotificationList() {
  const queue = useNotificationQueue();

  return (
    <AnimatePresence>
      {queue.entries.map(({ id, data }) => (
        <motion.div
          key={id}
          positionTransition
          initial={{ opacity: 0, y: 50, scale: 0.3 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{ opacity: 0, scale: 0.5, transition: { duration: 0.2 } }}
        >
          <Notification key={id} message={data.message} />
        </motion.div>
      ))}
    </AnimatePresence>
  );
}

Now when you want to trigger a notification from anywhere in your application you can import the hook and use it:

import { useNotificationQueue } from 'lib/notifications';

function MyComponent() {
  const notification = useNotificationQueue();

  function onClick() {
    notification.add('example', {
      title: 'Hello world',
    });
  }

  return <div onClick={onClick}>Show notification</div>;
}

Example

You can try the example by running yarn install and yarn start within the /example directory.

Testing

You can mock the notification system when using Storybook or writing tests. The createNotificationContext function returns a createMockNotificationQueue that can create a fake queue that can be passed into NotificationProvider:

const {
  NotificationProvider,
  createMockNotificationQueue,
} = createNotificationContext<Notification>();

In your tests you can create a queue, pass it in, and then inspect the queue to make sure events were fired. Here's an example using jest but you could do something similar with other mocking libraries, like sinon:

const queue = createMockNotificationQueue();
const addNotification = jest.spyOn(queue, 'add');

const { findByText } = render(
  <NotificationProvider queue={queue}>
    <TestComponent />
  </NotificationProvider>
);

Then watch addNotification for a new notification:

expect(addNotification).toHaveBeenCalledWith('test', {
  message: 'test',
});

Without mocking

If you prefer not to mock, you can pass in a mock queue and inspect the entries

const notifications = createMockImmutableQueue();

const { findByText } = render(
  <NotificationProvider queue={notifications}>
    <TestComponent />
  </NotificationProvider>
);

Then inspect notifications.entries, which will be an array of notifications:

expect(notifications.entries).toBe([
  {
    id: 'test',
    data: {
      message: 'Hello world',
    },
  },
]);

When you don't care about testing notifications

You can also leave out the queue if you don't need to listen for notifications:

const { findByText } = render(
  <NotificationProvider>
    <TestComponent />
  </NotificationProvider>
);