React is failing to display identical values for each item being mapped in the same sequence

I have implemented some standard mapping logic.

{MEMBERSHIPS.map((mItem, index) => (
                <TableCell
                  className="text-uppercase text-center"
                  colSpan={2}
                  padding="dense"
                  value={mItem.label}
                  key={mItem.key}
                >
                  <Button onClick={this.handleClickOpen}>{mItem.label}</Button>
                  <Dialog
                    disableBackdropClick
                    disableEscapeKeyDown
                    open={this.state.open}
                    onClose={this.handleClose}
                  >
                    <DialogTitle>
                      Choose bulk edit {mItem.label} status
                    </DialogTitle> 

...

The value of {mItem.label} is correctly displaying the headers, but when I reuse that key within the mapping statement, it only shows the last item in the array... I expected {mItem.label} to remain consistent wherever it is used.

https://codesandbox.io/s/kxrk5mnqjr

If you visit the above codesandbox... click on a header like seniors, juniors, or infants - this will trigger a button

<Button onClick={this.handleClickOpen}>{mItem.label}</Button>

A dialog will open where I want to display the same heading value {mItem.label}, but the displayed result does not match the header. For example, clicking the Seniors button should show the Seniors dialog text, but instead it displays "infants" in all instances.

Answer №1

An issue arises from using the same state value to control the opening and closing of all three dialogs this.state.open. When you click on one button, all three dialogs open simultaneously, with the last one appearing on top.

To resolve this problem:

  handleClickOpen = value => {
    this.setState({ [`open${value}`]: true });
  };

  handleClose = value => {
    this.setState({ [`open${value}`]: false });
  };

Additionally:

          <Button
            onClick={this.handleClickOpen.bind(this, mItem.value)}
          >
            {mItem.label}
          </Button>


         <Dialog
            disableBackdropClick
            disableEscapeKeyDown
            open={this.state[`open${mItem.value}`]}
            onClose={this.handleClose.bind(this, mItem.value)}
          >

          ...

For the full code visit https://codesandbox.io/s/pm0ovrvl97

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

Turn off Appbar padding at the top and bottom

I am looking to create a customized box within the Appbar that spans the full height, as illustrated in the image below: https://i.stack.imgur.com/CFMo0.jpg However, the default Appbar provides padding from all sides to its internal elements, leading to ...

Vue.js does not seem to be properly assigning attributes that are declared within the data object array

Trying to get a hang of vue.js and looking to create dynamic product cards using it: This is the snippet from my HTML file: <div id="app"> <card v-for="products in product" :productname="product.productname"></card> </div> Here&a ...

Is there a way to add a scrollbar to the ChartJS tooltip to avoid data

I'm currently working on a chartJS project where I have a callback function to display data in tooltips. However, as the data increases, the overflow section of the tooltip gets hidden from the canvas. Is there a solution to prevent this overflow and ...

The alignment of the first and second steps in Intro.js and Intro.js-react is off

There seems to be an issue here. Upon reloading, the initial step and pop-up appear in the upper left corner instead of the center, which is not what I anticipated based on the Intro.js official documentation. https://i.stack.imgur.com/ICiGt.png Further ...

submitting URL from dropdown menu without using the 'submit' button

My situation involves a dropdown list: @Html.DropDownList("InnerId", Model.GroupDropDownList, new { @class = "select_change" }) I am looking to achieve submitting the value when a user clicks on the selection without needing to select and then use a subm ...

The `XMLHttpRequest.prototype.open` function does not capture every single HTTP request visible in the chrome-dev-tools

While utilizing a third-party embedded code that initiates HTTP requests with a request header origin different from my own, I encountered an issue. Despite attempting to intercept these HTTP requests using XMLHttpRequest, they do not get intercepted. This ...

Tips for successfully importing .eot and .woff documents using Babel?

When attempting to start my project, I encountered the following error message (You may need an appropriate loader to handle this file type.) for .eot, .woff, .ttf, and .svg files: ERROR in ./src/styles/fonts/nm/icons/nm-icons.svg?aaf8685e87a6901c76c52d00 ...

Could React Native EXPO-CLI be utilized to enable video calling functionality?

Looking for a way to establish a video call connection between two clients, one using react Js and the other utilizing react native with expo-cli. Unsure if this is achievable under these circumstances. Any examples or alternatives would be greatly appre ...

Utilizing the Google Translate API within an ASP MVC framework to translate a div's content from English to Arabic

Currently, I am working on a small project that involves two divs: one for English and another for Arabic. Despite creating the project, I am encountering an issue with getting the translation from English to Arabic. Below is the code I have attempted, but ...

Tips for retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...

Step-by-step guide on utilizing the .change method in order to deactivate a

Can someone help me with a quick solution for this issue? I need to know how to disable a select option once the value has been changed. The option should be available on initial load, but after the user selects it for the first time, it should be disable ...

Is it possible to forecast an on click event using jQuery?

I have encountered a specific issue. Within my code, there are certain elements, specifically <li> elements, that undergo a particular operation triggered by a click event: $('.panelTabs li').on('click', function () { // ..som ...

Filter the array and determine the number of elements in the filtered array

I am looking to filter the contents of two arrays and then count the elements where "isimplemented: 'Yes'" is true: const array1 = [{ProjectName: "IT", Department: "Software"}] const array2 = [{Name: "IT", isimplemented: "Yes"}] The method I at ...

Toggle Visibility of Elements with Javascript and Html

I've been working on implementing a "Show All / Hide All" feature. Currently, clicking on the text opens the image and text individually. However, I am looking to add a functionality for expanding all divs at once. To see how it currently functions, ...

Explore RxJs DistinctUntilChanged for Deep Object Comparison

I have a scenario where I need to avoid redundant computations if the subscription emits the same object. this.stateObject$ .pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 }))) .subscribe(obj =& ...

Guide on how to add multiple options to a select element in HTML using prototype.js

What is the best way to add multiple options to a select tag in HTML using prototype js? Appreciate your help. ...

Is it possible for you to enter "1.00" instead of just 1 when using the input type as number?

I am using Polymer paper-input and I would like to ensure that my input with type "number" always displays 2 decimal points, even when it is a whole number. Instead of just displaying as "1", I want it to be shown as "1.00" at all times. I have tried sett ...

The Axios request will be caught in the catch block if it encounters a response status code between 400 and 500

When the server sends a status code between 400 and 500, Axios will skip the `.then()` block and go directly to the `catch` block. However, if the server sends a status code in the range of 200, Axios will accept it. This code snippet represents the client ...

Load HTML table values dynamically with Ajax post page load in PHP

My goal is to retrieve the connectivity status of available servers in a database on a PHP page. <tbody> <?php foreach ($data['servers'] as $server) { ?> <tr> <td class=""><?php echo $server->server_ ...

How to Handle Empty Input Data in JQuery Serialization

Having an issue with a form that triggers a modal window containing another form when a button is clicked. The second form includes an input field and send/cancel buttons. The goal is to serialize the data from the modal form and send it to a server using ...