DEV Community

James Parker
James Parker

Posted on

Getting Started with Simple React Notifications: Building Toast Notifications

Simple React Notifications is a lightweight and easy-to-use library for displaying toast notifications in React applications. It provides a simple API for showing temporary messages with minimal configuration, making it perfect for beginners who want to add notifications to their apps quickly. This guide walks through setting up and creating toast notifications using Simple React Notifications with React, from installation to a working implementation. This is part 37 of a series on using Simple React Notifications with React.

Prerequisites

Before you begin, make sure you have:

  • Node.js version 14.0 or higher installed
  • npm, yarn, or pnpm package manager
  • A React project (version 16.8 or higher) or create-react-app setup
  • Basic knowledge of React hooks (useState)
  • Familiarity with JavaScript/TypeScript

Installation

Install Simple React Notifications using your preferred package manager:

npm install simple-react-notifications
Enter fullscreen mode Exit fullscreen mode

Or with yarn:

yarn add simple-react-notifications
Enter fullscreen mode Exit fullscreen mode

Or with pnpm:

pnpm add simple-react-notifications
Enter fullscreen mode Exit fullscreen mode

After installation, your package.json should include:

{
  "dependencies": {
    "simple-react-notifications": "^2.0.0",
    "react": "^18.0.0",
    "react-dom": "^18.0.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

Project Setup

Set up the notification provider in your main entry file:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { NotificationProvider } from 'simple-react-notifications';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <NotificationProvider>
      <App />
    </NotificationProvider>
  </React.StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

First Example / Basic Usage

Let's create a simple notification component. Create a new file src/NotificationExample.jsx:

// src/NotificationExample.jsx
import React from 'react';
import { useNotifications } from 'simple-react-notifications';

function NotificationExample() {
  const { showSuccess, showError, showInfo, showWarning } = useNotifications();

  return (
    <div style={{ padding: '20px' }}>
      <h2>Notification Examples</h2>
      <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
        <button onClick={() => showSuccess('Operation completed successfully!')}>
          Success
        </button>
        <button onClick={() => showError('Something went wrong!')}>
          Error
        </button>
        <button onClick={() => showInfo('Here is some information.')}>
          Info
        </button>
        <button onClick={() => showWarning('Please review your input.')}>
          Warning
        </button>
      </div>
    </div>
  );
}

export default NotificationExample;
Enter fullscreen mode Exit fullscreen mode

Update your App.jsx:

// src/App.jsx
import React from 'react';
import NotificationExample from './NotificationExample';
import './App.css';

function App() {
  return (
    <div className="App">
      <NotificationExample />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

This creates basic toast notifications that appear when you click the buttons and automatically disappear after a few seconds.

Understanding the Basics

Simple React Notifications uses a hook-based API where:

  • useNotifications: Hook that provides notification functions
  • showSuccess: Show a success notification
  • showError: Show an error notification
  • showInfo: Show an info notification
  • showWarning: Show a warning notification
  • NotificationProvider: Provider component that manages notification state

Key concepts:

  • Provider Component: NotificationProvider must wrap your app
  • Hook Usage: Use useNotifications hook in components to access notification functions
  • Automatic Dismissal: Notifications automatically disappear after a set duration
  • Simple API: Minimal configuration required to get started
  • Customization: Basic customization options available

Here's an example with custom options:

// src/CustomNotificationExample.jsx
import React from 'react';
import { useNotifications } from 'simple-react-notifications';

function CustomNotificationExample() {
  const { showSuccess, showError } = useNotifications();

  const showCustomSuccess = () => {
    showSuccess('Custom success message', {
      duration: 5000,
      position: 'top-right'
    });
  };

  const showCustomError = () => {
    showError('Custom error message', {
      duration: 7000,
      position: 'bottom-left'
    });
  };

  return (
    <div style={{ padding: '20px' }}>
      <h2>Custom Notification Examples</h2>
      <div style={{ display: 'flex', gap: '10px' }}>
        <button onClick={showCustomSuccess}>Custom Success</button>
        <button onClick={showCustomError}>Custom Error</button>
      </div>
    </div>
  );
}

export default CustomNotificationExample;
Enter fullscreen mode Exit fullscreen mode

Practical Example / Building Something Real

Let's build a form component with notification feedback:

// src/FormWithNotifications.jsx
import React, { useState } from 'react';
import { useNotifications } from 'simple-react-notifications';

function FormWithNotifications() {
  const { showSuccess, showError, showInfo } = useNotifications();
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    message: ''
  });
  const [errors, setErrors] = useState({});

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  const validateForm = () => {
    const newErrors = {};
    if (!formData.name.trim()) {
      newErrors.name = 'Name is required';
    }
    if (!formData.email.trim()) {
      newErrors.email = 'Email is required';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = 'Invalid email format';
    }
    if (!formData.message.trim()) {
      newErrors.message = 'Message is required';
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!validateForm()) {
      showError('Please fill in all fields correctly.');
      return;
    }

    showInfo('Submitting form...', { duration: 2000 });

    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 2000));

      showSuccess('Form submitted successfully!', { duration: 3000 });

      // Reset form
      setFormData({ name: '', email: '', message: '' });
      setErrors({});
    } catch (error) {
      showError('Failed to submit form. Please try again.', { duration: 4000 });
    }
  };

  return (
    <div style={{ padding: '20px', maxWidth: '500px', margin: '0 auto' }}>
      <h2>Contact Form with Notifications</h2>
      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: '16px' }}>
          <label
            htmlFor="name"
            style={{
              display: 'block',
              marginBottom: '4px',
              fontWeight: '500'
            }}
          >
            Name *
          </label>
          <input
            type="text"
            id="name"
            name="name"
            value={formData.name}
            onChange={handleInputChange}
            style={{
              width: '100%',
              padding: '8px',
              border: `1px solid ${errors.name ? '#dc3545' : '#ddd'}`,
              borderRadius: '4px',
              fontSize: '14px',
              boxSizing: 'border-box'
            }}
          />
          {errors.name && (
            <div
              style={{
                color: '#dc3545',
                fontSize: '12px',
                marginTop: '4px'
              }}
            >
              {errors.name}
            </div>
          )}
        </div>

        <div style={{ marginBottom: '16px' }}>
          <label
            htmlFor="email"
            style={{
              display: 'block',
              marginBottom: '4px',
              fontWeight: '500'
            }}
          >
            Email *
          </label>
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleInputChange}
            style={{
              width: '100%',
              padding: '8px',
              border: `1px solid ${errors.email ? '#dc3545' : '#ddd'}`,
              borderRadius: '4px',
              fontSize: '14px',
              boxSizing: 'border-box'
            }}
          />
          {errors.email && (
            <div
              style={{
                color: '#dc3545',
                fontSize: '12px',
                marginTop: '4px'
              }}
            >
              {errors.email}
            </div>
          )}
        </div>

        <div style={{ marginBottom: '16px' }}>
          <label
            htmlFor="message"
            style={{
              display: 'block',
              marginBottom: '4px',
              fontWeight: '500'
            }}
          >
            Message *
          </label>
          <textarea
            id="message"
            name="message"
            value={formData.message}
            onChange={handleInputChange}
            rows={4}
            style={{
              width: '100%',
              padding: '8px',
              border: `1px solid ${errors.message ? '#dc3545' : '#ddd'}`,
              borderRadius: '4px',
              fontSize: '14px',
              resize: 'vertical',
              fontFamily: 'inherit',
              boxSizing: 'border-box'
            }}
          />
          {errors.message && (
            <div
              style={{
                color: '#dc3545',
                fontSize: '12px',
                marginTop: '4px'
              }}
            >
              {errors.message}
            </div>
          )}
        </div>

        <button
          type="submit"
          style={{
            width: '100%',
            padding: '10px',
            backgroundColor: '#007bff',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer',
            fontSize: '16px'
          }}
        >
          Submit
        </button>
      </form>
    </div>
  );
}

export default FormWithNotifications;
Enter fullscreen mode Exit fullscreen mode

Now create a custom hook for reusable notifications:

// src/hooks/useNotificationHelpers.js
import { useCallback } from 'react';
import { useNotifications } from 'simple-react-notifications';

export const useNotificationHelpers = () => {
  const { showSuccess, showError, showInfo, showWarning } = useNotifications();

  const notifyFormSuccess = useCallback((message) => {
    showSuccess(message, {
      duration: 3000,
      position: 'top-right'
    });
  }, [showSuccess]);

  const notifyFormError = useCallback((message) => {
    showError(message, {
      duration: 5000,
      position: 'top-right'
    });
  }, [showError]);

  const notifyApiSuccess = useCallback((message) => {
    showSuccess(message, {
      duration: 4000,
      position: 'top-center'
    });
  }, [showSuccess]);

  const notifyApiError = useCallback((message) => {
    showError(message, {
      duration: 6000,
      position: 'top-center'
    });
  }, [showError]);

  return {
    notifyFormSuccess,
    notifyFormError,
    notifyApiSuccess,
    notifyApiError,
    showInfo,
    showWarning
  };
};
Enter fullscreen mode Exit fullscreen mode

Update your App.jsx:

// src/App.jsx
import React from 'react';
import FormWithNotifications from './FormWithNotifications';
import './App.css';

function App() {
  return (
    <div className="App">
      <FormWithNotifications />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

This example demonstrates:

  • Form validation with notification feedback
  • Success and error notifications
  • Loading state notifications
  • Custom notification durations
  • Integration with form submission

Common Issues / Troubleshooting

  1. Notifications not displaying: Ensure NotificationProvider wraps your app at the root level. The provider must be a parent of components using useNotifications.

  2. Hook not working: Make sure you're calling useNotifications inside a component that's a child of NotificationProvider. The hook cannot be used outside the provider context.

  3. Notifications appearing in wrong position: Use the position option when calling notification functions. Available positions may include 'top-right', 'top-left', 'top-center', 'bottom-right', 'bottom-left', 'bottom-center'.

  4. Notifications not auto-dismissing: Check the duration option. Set a duration in milliseconds (e.g., 3000 for 3 seconds). If duration is not set, notifications may use a default duration.

  5. Multiple notifications stacking: Simple React Notifications handles multiple notifications automatically. They will stack based on the position setting.

  6. Styling issues: Simple React Notifications comes with default styles. You can customize the appearance by passing style options or using CSS to override default styles.

Next Steps

Now that you have a basic understanding of Simple React Notifications:

  • Learn about advanced customization options
  • Explore different notification positions and animations
  • Implement notification queues and limits
  • Add custom notification components
  • Integrate with React Context for global notification management
  • Learn about other notification libraries (react-toastify, notistack)
  • Check the official repository: https://github.com/alexpermyakov/simple-react-notifications
  • Look for part 38 of this series for more advanced topics

Summary

You've successfully set up Simple React Notifications in your React application and created toast notifications for user feedback. Simple React Notifications provides a simple, lightweight solution for displaying temporary messages with minimal configuration.

SEO Keywords

simple-react-notifications
React toast notifications
simple-react-notifications tutorial
React notification library
simple-react-notifications installation
React toast messages
simple-react-notifications example
React alert notifications
simple-react-notifications setup
React notification hooks
simple-react-notifications customization
React notification system
simple-react-notifications provider
React toast library
simple-react-notifications getting started

Top comments (0)