Display modal within a React list

I need to display a list of items with an edit button for each item, which should trigger a modal showing the details of that specific item. Initially, I had a single modal component in the parent element and passing the visible values to the parent state when clicking the edit button would cause the entire list to re-render. This was not ideal as the list could contain hundreds of items. My current solution involves associating a modal with each item in the list, but this duplicates unnecessary code.

While the code is too extensive to include here, below are the essential sections:

import Modal from '../Modal';

const CustomCard = ({
  ...omitted
}) => {
  const [editCustomerModal, setEditCustomerModal] = useState(false);

  const onEditModal = () => {
    setEditCustomerModal(true);
  };

  return (
    <>
      <CustomerModal
        onSuccess={handleUpdateCustomer}
        onCancel={handleCancelModal}
        visible={editCustomerModal}
        title="Edit Customer"
        details={{
          .. ommitted
        }}
      />
      <Card />
         ....data
      </Card>
    </>
  );
};

export default CustomCard;
import CustomCard from '../CustomerCard/index';

const CustomList = ({ dataSource }) => {
  
  return (
    <div>
      {dataSource?.map(i => (
        <CustomCard
          ...props ommitted
        />
      ))}
    </div>
  );
};

export default CustomerList;
import CustomerList from './components/CustomerList/index';

const CustomersPage = () => {
     const [editCustomerModal, setEditCustomerModal] = useState(false);
     const [editCustomer, setEditCustomer] = useState(null);

 return (
   <>

     <Modal
       onSuccess={handleSaveCustomerEdit}
       onCancel={handleCancelCustomerEdit}
       visible={editCustomerModal}
       details={editCustomer}
     />
       <CustomerList
         dataSource={data}

       />
     </div>
     {/* </ModalContext.Provider> */}
   </>
 );

export default CustomersPage;

Answer №1

To customize your modal, you can set up a useState variable to store the specific data you wish to pass.

Here is an example:

import ProductList from './components/ProductList/index';

import Modal from './components/AddProductModal';

const ProductsPage = () => {
    const [editProductModal, setEditProductModal] = useState(false);
    const [editProduct, setEditProduct] = useState(null);
    const [selectedItem, setSelectedItem] = useState(null);

    return (
        <>
            <Modal
                onSuccess={handleSaveProductEdit}
                onCancel={handleCancelProductEdit}
                visible={editProductModal}
                details={editProduct}
                selectedItem={selectedItem}
            />

            {productData?.map(prod => (
                <CustomCard ...otherProps omitted setSelectedItem={setSelectedItem}/>
                // Inside CustomCard component, trigger the event to set the selected item that will be passed to the modal
                // Be cautious with null object. Always use selectedItem?.property
            ))}
        </>
    );
};

export default ProductsPage;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The gltf file does not appear to be displaying properly within a React Next.js environment

I'm facing an issue while attempting to load a gltf file in a nextjs application using threejs. The process doesn't seem to work when running it within a nextjs application on a react project. Here's the configuration I used for next.js with ...

Is there a way to display tiff files in Google Chrome?

I've been struggling with this problem for over 48 hours now, tirelessly searching for a solution. The issue lies within an application built using the ext.net framework on the front end. Specifically, I'm encountering difficulties when it comes ...

AngularJS special feature: enhance controllers and views by adding notification capabilities

What is the most efficient method for integrating common notification features into necessary controllers in AngularJS? The objective is to establish local notifications that can be effortlessly included or removed from any controller. Key factors includ ...

Begin the input box with some text

Currently, I am trying to incorporate a form field that automatically adds "http://" when clicked or typed into by a user. Below is the code snippet I have been using: <script type="text/javascript"> var input = $( "#website" ); input.val( input ...

Implementing a Collapse and Expand All feature within an Accordion Component

Hey there! I've been attempting to implement a Collapse All feature on my accordion but am having trouble figuring it out. The resource I've been referencing is this one. I've searched around and noticed that this accordion setup is a bit d ...

What is the most effective way to leverage rxjs for executing multiple asynchronous fetch operations in one go using a forEach strategy?

As a newcomer to React, I have been assigned the task of modifying an existing application that already makes multiple API calls. The current pattern in use is illustrated below. For example, if an action mapperActions.selectPolygon of type CaseReducerActi ...

Populate a form with database information to pre-fill the fields

So I have this web form built with HTML, and there are certain values within the form that can be changed by the user. To ensure these changes are saved, I'm storing them in a database. My goal is to have the form automatically filled with the data fr ...

How can a component be dynamically rendered in React?

I'm interested in exploring alternative approaches to accomplishing the same task. My desired outcome is as follows: Menu Item 1 Menu Item 2 Menu Item 3 Target (Where component should be displayed) When a menu item is clicked, I want the associate ...

Is it possible for me to identify the original state of a checkbox when the page first loaded, or the value it was reset to when `reset()` was

When a webpage is loaded, various input elements can be initialized as they are declared in the HTML. If the user modifies some of the input values and then resets the form using reset(), the form goes back to its initially loaded state. I'm curious, ...

Encountering issues while running the npm build command due to exporting async functions in React

In my React project, I am utilizing async functions and have created a file named apiRequest.js structured like this: const axios = require('axios'); const serverURL = "http://localhost:8080" getInfo = async function ({email}) { try { r ...

What is the best way to make two buttons align next to each other in a stylish and elegant manner

Currently, I am diving into the world of glamorous, a React component styling module. My challenge lies in styling two buttons: Add and Clear. The goal is to have these buttons on the same row with the Clear button positioned on the left and the Add button ...

Implementing onClick event handling in Material UI components using Typescript

I am attempting to pass a function that returns another function to material UI's onTouchTap event: <IconButton onTouchTap={onObjectClick(object)} style={iconButtonStyle} > <img alt={customer.name} className="object-img" src={obj ...

The function is failing to return a false value

I have encountered a problem with my code - it works fine in Chrome but not in IE or Firefox. I've tried using return false; and event.preventDefault() but they don't seem to be effective in Firefox. The issue arises when the button grabs informa ...

What is the reason behind Meteor automatically updating a record without the need to run a "Meteor.call" function for an update?

I am currently developing a Meteor.js application and while I have grasped the basic concepts of Meteor, I feel like I might be missing something when it comes to its reactivity principles. Using angular-meteor, I am utilizing a $scope variable in my view ...

Execute the Apollo mutation when the component first renders using the useEffect hook

I'm trying to create an order when a MUI dialogue is opened. I attempted to use useEffect with an empty dependency, but for some reason the mutation doesn't resolve before the setState action. The activeOrder always returns a Promise that is fulf ...

Using the fetch method to consume a RapidAPI JSON response

Currently, I am in the process of learning React Native and have initiated a project for that purpose. In this project, I have integrated RapidAPI (link: ) to fetch necessary data. Upon hitting the API, I receive a 200OK status, but unfortunately, I am fa ...

There seems to be a clash between Modal Semantic UI React and Bootstrap causing issues

I created a project using .net core MVC. I have integrated the semantic-ui-react modal by importing its library and linking the CSS for it to function properly. However, I encountered an issue where the bootstrap CSS was conflicting with the CDN for semant ...

The download functionality in HTML5 is not functioning properly, so users are forced to rename files when downloading

For weeks, I've been struggling to change the name of the downloaded file. Despite my efforts, instead of being named Chrysanthemum.jpg, it ends up as a hash of the file like 241693260.jpg In my backend setup, I utilize Node.js and Express.js for man ...

ASP.net is encountering difficulty locating a specific JavaScript function

Seeking assistance to comprehend the issue, I have devoted countless hours scouring Google for a resolution. Current tools in use: ASP.NET entity framework Within a view, the following code is utilized: <button type="button" id="btnGraf ...

The connection to the Docker Container on localhost is not established

I am currently working on setting up a React app that communicates with a json server within a docker container. Below is the Dockerfile configuration I am using: # base image FROM node:alpine # set working directory WORKDIR '/app' # add `/app ...