,

Creating Pop Up Modals with React in NextJs 13 | Tutorial #5

Posted by

React Modal: Create Pop Up Modals in NextJs 13

React Modal: Create Pop Up Modals in NextJs 13

In this article, we will learn how to create pop up modals in NextJs 13 using React Modal library. Modals are a common UI element used to display important information, gather user input, or confirm actions. With React Modal, we can easily create and manage modals in our NextJs 13 application.

Setting up NextJs 13

If you haven’t already set up NextJs 13, you can do so by following the official documentation at https://nextjs.org/docs/getting-started. Once you have NextJs 13 installed and a basic project set up, you can proceed with adding React Modal to your project.

Installing React Modal

To install React Modal, you can use npm or yarn. Open your terminal and navigate to your NextJs 13 project directory. Then, run the following command:

npm install react-modal
  

After the installation is complete, you can import React Modal in your components and start using it to create pop up modals.

Creating a Pop Up Modal

Let’s create a simple example of a pop up modal in NextJs 13 using React Modal. First, we will create a new component called Modal:

<!-- Modal.js -->

import React from 'react';
import Modal from 'react-modal';

const customStyles = {
  content: {
    top: '50%',
    left: '50%',
    right: 'auto',
    bottom: 'auto',
    marginRight: '-50%',
    transform: 'translate(-50%, -50%)',
  },
};

Modal.setAppElement('#__next');

export default function ExampleModal() {
  const [modalIsOpen, setIsOpen] = React.useState(false);

  function openModal() {
    setIsOpen(true);
  }

  function closeModal() {
    setIsOpen(false);
  }

  return (
    
      
      
        <h2>Hello Modal</h2>
        <button onClick={closeModal}>Close Modal</button>
      
    
  );
}
  

In this example, we have created a Modal component that uses React Modal to create and manage a pop up modal. We have defined custom styles for the modal and set up open and close functions to control the modal’s visibility.

Using the Modal Component

After creating the Modal component, you can now use it in any of your NextJs 13 pages or components. Simply import the Modal component and place it within your application where you want the pop up modal to appear.

With React Modal, creating and managing pop up modals in NextJs 13 is straightforward and intuitive. By following the steps outlined in this article, you can enhance your NextJs 13 application with pop up modals for various use cases.

Thank you for reading! If you have any questions or feedback, feel free to reach out to us.