Modal In Next.Js

To implement the functionality of opening a modal for "Edit" or "Add" actions in your Next.js application, follow these steps:

1. Create a Modal Component
Create a reusable modal component that can be opened or closed dynamically.

// components/Modal.js
import React from 'react';
import styles from './Modal.module.css'; // Create a CSS file for modal styling

const Modal = ({ isOpen, onClose, children }) => {
  if (!isOpen) return null;

  return (
    <div className={styles.modalOverlay}>
      <div className={styles.modalContent}>
        <button className={styles.closeButton} onClick={onClose}>
          &times;
        </button>
        {children}
      </div>
    </div>
  );
};

export default Modal;
2. Style the Modal
Create a CSS module file (Modal.module.css) for modal styling.


/* Modal.module.css */
.modalOverlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modalContent {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
  max-width: 90%;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.closeButton {
  background: transparent;
  border: none;
  font-size: 1.5rem;
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
}
3. Update UserPage to Use the Modal
Update the UserPage component to include modal handling.


import React, { useState } from 'react';
import Modal from './Modal'; // Import your modal component

export const UserPage = () => {
  const [isModalOpen, setModalOpen] = useState(false);
  const [currentUser, setCurrentUser] = useState(null); // Store user data for editing

  const handleEdit = (user) => {
    setCurrentUser(user);
    setModalOpen(true);
  };

  const handleAdd = () => {
    setCurrentUser(null); // Clear current user for "Add" action
    setModalOpen(true);
  };

  const handleCloseModal = () => {
    setModalOpen(false);
  };

  return (
    <div>
      <button onClick={handleAdd}>Add New User</button>
      <Modal isOpen={isModalOpen} onClose={handleCloseModal}>
        <div className="form-container">
          <h2>{currentUser ? 'Edit User' : 'Add New User'}</h2>
          <form className="add-user-form">
            <div className="form-group">
              <label>First Name</label>
              <input
                type="text"
                placeholder="First name"
                defaultValue={currentUser?.firstName || ''}
              />
            </div>
            <div className="form-group">
              <label>Last Name</label>
              <input
                type="text"
                placeholder="Last name"
                defaultValue={currentUser?.lastName || ''}
              />
            </div>
            <div className="form-group">
              <label>Email</label>
              <input
                type="email"
                placeholder="Email"
                defaultValue={currentUser?.email || ''}
              />
            </div>
            <div className="form-group">
              <label>Phone</label>
              <input
                type="tel"
                placeholder="(201) 555-0123"
                defaultValue={currentUser?.phone || ''}
              />
            </div>
            <div className="form-group">
              <label>Type</label>
              <input
                type="text"
                placeholder="Type"
                defaultValue={currentUser?.type || ''}
              />
            </div>
            <div className="form-group">
              <label>Status *</label>
              <input
                type="text"
                placeholder="Status"
                defaultValue={currentUser?.status || ''}
                required
              />
            </div>
            <div className="form-group">
              <label>Set Password</label>
              <input
                type="password"
                placeholder="Set Password"
              />
            </div>
            <div className="form-group">
              <label>User Role *</label>
              <input
                type="text"
                placeholder="User Role"
                defaultValue={currentUser?.role || ''}
                required
              />
            </div>
            <div className="form-buttons">
              <button type="submit" className="submit">
                Submit
              </button>
              <button
                type="button"
                className="dismiss"
                onClick={handleCloseModal}
              >
                Dismiss
              </button>
            </div>
          </form>
        </div>
      </Modal>
    </div>
  );
};
4. Trigger the Edit and Delete Handlers
In your parent component or list view, bind the handleEdit and handleDelete methods to user actions (e.g., buttons in a table).


<button onClick={() => handleEdit(user)}>Edit</button>
<button onClick={() => handleDelete(user)}>Delete</button>


Now, clicking "Edit" or "Add New User" will open the modal with the appropriate form and data. 



        
Waqas Shamraiz

Student at Federal Urdu University of Arts, Science & Technology, Islamabad.

2 周

Good work ??

要查看或添加评论,请登录

MUNEM H.的更多文章

  • React Native Location

    React Native Location

    You can use the Google Maps Geocoding API to convert latitude and longitude into a location name programmatically in a…

  • React Navigation vs. React Native Navigation:

    React Navigation vs. React Native Navigation:

    React Navigation vs. React Native Navigation: Which One Should You Use? Both React Navigation and React Native…

  • Lambda function AWS

    Lambda function AWS

    To create a Lambda function that listens to changes in a hub for connection status and then triggers a change in…

  • RTK in React

    RTK in React

    To use RTK (Redux Toolkit) in React Native, you can follow these steps: Install the necessary dependencies: npm install…

  • WHY Test Cases For React Native

    WHY Test Cases For React Native

    Writing test cases for a React Native app is essential for ensuring the reliability and stability of your application…

  • Improve React Native App Performance

    Improve React Native App Performance

    To improve the performance of a React Native app, you can follow these key steps: Optimize Rendering: Use the FlatList…

  • Threads in React Native

    Threads in React Native

    React Native uses a single JavaScript thread to execute the application code, which is the main thread. JavaScript, as…

  • Custom Hook

    Custom Hook

    Creating custom Hooks in #React & #React_Native is a powerful technique that allows developers to encapsulate logic and…

  • React & React Native Hooks

    React & React Native Hooks

    In #React and #ReactNative, #hooks are a powerful feature that allows developers to use state and other React features…

    3 条评论
  • Best practices for building scalable React and React Native applications.

    Best practices for building scalable React and React Native applications.

    Scalability is a crucial factor in building successful React and React Native applications. As these #frameworks gain…

    2 条评论