Creating a Modal Component in React: 3 Examples

Explore 3 practical examples of creating a modal component in React, perfect for beginners and beyond.
By Taylor

Introduction

Creating a modal component in React can enhance your application’s user interface by providing a way to display information or gather user input without navigating away from the current page. In this guide, we’ll walk through three diverse examples of creating a modal component in React, each tailored to different use cases. Whether you’re looking to implement a simple alert, a confirmation dialog, or a form, these examples will provide you with the foundational knowledge to get started.

Example 1: Basic Alert Modal

Context

This example demonstrates a simple alert modal that displays a message to the user. It’s useful for notifications and quick alerts without requiring any user input.

import React, { useState } from 'react';

const AlertModal = () => {
  const [isOpen, setIsOpen] = useState(false);

  const openModal = () => setIsOpen(true);
  const closeModal = () => setIsOpen(false);

  return (
    <div>
      <button onClick={openModal}>Show Alert</button>
      {isOpen && (
        <div className="modal">
          <div className="modal-content">
            <h2>Alert!</h2>
            <p>This is an alert message.</p>
            <button onClick={closeModal}>Close</button>
          </div>
        </div>
      )}
    </div>
  );
};

export default AlertModal;

Notes

  • You can add CSS styles to position the modal and make it look more appealing.
  • Consider integrating animations for a smoother user experience.

Example 2: Confirmation Modal

Context

This example illustrates a confirmation modal that asks the user to confirm an action, such as deleting an item. It’s useful for ensuring that users don’t accidentally perform critical actions.

import React, { useState } from 'react';

const ConfirmationModal = () => {
  const [isOpen, setIsOpen] = useState(false);

  const openModal = () => setIsOpen(true);
  const closeModal = () => setIsOpen(false);
  const handleConfirm = () => {
    alert('Action confirmed!');
    closeModal();
  };

  return (
    <div>
      <button onClick={openModal}>Delete Item</button>
      {isOpen && (
        <div className="modal">
          <div className="modal-content">
            <h2>Confirm Action</h2>
            <p>Are you sure you want to delete this item?</p>
            <button onClick={handleConfirm}>Yes</button>
            <button onClick={closeModal}>No</button>
          </div>
        </div>
      )}
    </div>
  );
};

export default ConfirmationModal;

Notes

  • This modal can be easily extended to perform different actions based on user input.
  • You may want to add additional styling or animations to enhance the user experience.

Example 3: Form Modal

Context

In this example, we create a modal that contains a form for user input. This is useful for situations like adding new items or collecting information.

import React, { useState } from 'react';

const FormModal = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [formData, setFormData] = useState({ name: '', email: '' });

  const openModal = () => setIsOpen(true);
  const closeModal = () => setIsOpen(false);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Name: ${formData.name}, Email: ${formData.email}`);
    closeModal();
  };

  return (
    <div>
      <button onClick={openModal}>Open Form</button>
      {isOpen && (
        <div className="modal">
          <div className="modal-content">
            <h2>Submit Your Info</h2>
            <form onSubmit={handleSubmit}>
              <input 
                type="text" 
                name="name" 
                placeholder="Your Name" 
                value={formData.name} 
                onChange={handleChange} 
                required
              />
              <input 
                type="email" 
                name="email" 
                placeholder="Your Email" 
                value={formData.email} 
                onChange={handleChange} 
                required
              />
              <button type="submit">Submit</button>
              <button type="button" onClick={closeModal}>Cancel</button>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default FormModal;

Notes

  • This form can be adjusted to include more fields or validation as needed.
  • Consider adding error handling and user feedback upon submission for a better experience.

Conclusion

These examples of creating a modal component in React provide a solid foundation for enhancing user interactions in your applications. Feel free to customize and expand upon these examples to fit your specific needs!