Preserving the button's state when clicked

Here is my code snippet:

<blink>

  const [thisButtomSelected, setThisButtomSelected] = useState(false);
  var thisButton = [];

  const onAttributeClick = (e) => {
    thisButton[e.currentTarget.value] = { thisID: e.currentTarget.id, thisName: e.currentTarget.name };
    setThisButtomSelected(thisButton[e.currentTarget.value]);
  }
  return(
    <div>
      {data.item.attributes.map((attribute, index) => (
        <div key={index} >
          <p id={attribute.id}>{attribute.name}:</p>

          <ul className="choose-attribute-container-ul">
            {attribute.items.map((item) => (

              <li key={item.id}>
                <button
                  value={item.value}
                  id={item.id}
                  name={attribute.name}
                  className={_.isEqual(thisButtomSelected, { thisID: item.id, thisName: attribute.name }) ? 'attribute-button-selected' : 'attribute-button'}
                  onClick={onAttributeClick}
                >
                  {item.displayValue}
                </button>
              </li>
            ))}
          </ul>
        </div>
      ))}
    </div>
  )

</blink>

Although the current implementation works fine, there is a minor issue where previously selected buttons get unclicked when a new button is clicked. I am trying to figure out how to preserve the state of the first selected button even after clicking on another one.

  1. Only one button can be active for each attribute
  2. The buttons' names should be utilized

Answer №1

To ensure that all buttons are saved and retained, consider storing them in an array like this:

  const [selectedButtons, setSelectedButtons] = useState([]);

  var customButton = [];
  
  const onButtonClick = (e) => {
      customButton[e.currentTarget.value] = { buttonID: e.currentTarget.id, buttonName: e.currentTarget.name }
  
      setSelectedButtons([...selectedButtons, customButton[e.currentTarget.value]]);
  
  }
  return(
              <div>
                  {data.product.buttons.map((button, index) => (
                      <div key={index} >
                          <p id={button.id}>{button.name}:</p>
  
                          <ul className="choose-buttons-container-ul">
                              {button.items.map((item) => (
  
                                  <li key={item.id}>
                                      <button
                                          value={item.value}
                                          id={item.id}
                                          name={button.name}
                                          className={selectedButtons.find(el => el.buttonID === item.id && el.buttonName === button.name) ? 'button-selected' : 'button-normal'}
                                          onClick={onButtonClick}
                                      >

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

Can PHP send back data to AJAX using variables, possibly in an array format?

My goal is to transmit a datastring via AJAX to a PHP page, receive variables back, and have jQuery populate different elements with those variables. I envision being able to achieve this by simply writing: $('.elemA').html($variableA); $('. ...

Transforming an AJAX call into a reusable function

My goal is to simplify my ajax calls by creating a function that can be reused. Although I'm unsure if I'm doing it correctly, I would like to attempt this approach. <script> $(document).ready(function(){ var reg_no=$("#reg_no").va ...

Showing child elements within a div using AngularJS

I am eager to create a straightforward AngularJS website that will showcase an initially hidden HTML element along with all of its children. Below is the HTML structure snippet I plan to use: <div class="hiddenStuff"> <h3>Game Over</h3&g ...

When I try to start the editor with HTML content using the convertFromHTML method, I encounter an error stating that

I am encountering an error when trying to initialize my Editor state with a HTML markup. at renderToString (/home/al/Documents/node/admin-next/node_modules/react-dom/cjs/react-dom-server.node.development.js:3988:27) at render (/home/al/Documents/node/admin ...

Custom MUI theme fails to supersede palette settings

I am currently experimenting with overriding the default theme in MUI for a small test before integrating it into a larger project. Despite following the documentation, I am facing issues with applying the new colors from my theme to a child component. My ...

Alert: Parser error in JSONP!

$.ajax({ type: "GET", dataType: "jsonp", jsonpCallback: "jsoncallback", //async: true , data: { // some other data here }, url: "http://mywebsite.com/getRequest.php", success: function(response ...

Tips for excluding the "use client" term in the upcoming 13 using Material UI

I'm encountering an issue while developing a server-rendered app in next.js 13. Whenever I attempt to import a material ui component within the layout.jsx or any other file, I encounter an error. The error message states that I am importing a componen ...

Using the MERN stack in conjunction with Socket for MongoDB provides the ability to display real-time data on the frontend directly

As I work on setting up a website using the MERN stack, my backend will continuously fetch data from APIs and sockets to save it in a MongoDB database. For the frontend React, I aim to display and update this data in real-time using Socket. I have concern ...

The occurrence of an Error [ERR_HTTP_HEADERS_SENT] arises due to the inability to modify headers after they have already been sent to

I have set axios to use credentials globally: axios.defaults.withCredentials = true However, when using the following useEffect hook, an error in the title is raised: useEffect(() => { const initAuth = async (): Promise<void> => { ...

The content in the div tag isn't showing up properly because of Ajax

I am facing an issue with my Ajax query. Even though I can retrieve the results by posting, they are not displaying in the designated div tag on mainInstructor2.php. Instead, the results are showing up on a different page - specifically, on InstructorStude ...

Tips for storing arrays in AngularJS with JavaScript

I am new to using JavaScript. I have a function that stores objects in an array to an Angular model. Here is an example: function getSpec(){ debugger var i; for(i=0;i<main.specifications.length;i++){ main.newProduct.Specification= ( ...

Don't allow users to switch views without saving their changes

We are working with a Backbone.js application that presents various forms to users. Our goal is simple: if a user navigates away from the page without saving the completed form, we need to show a confirmation dialog. When dealing with traditional forms, i ...

Using JavaScript and HTML, showcase the capital city of a country along with its corresponding continent

As a newcomer to this platform, I am excited to share a code snippet that I have created using HTML and JavaScript. The code generates a textbox in an HTML page where users can type the name of a country. Upon inputting the country's name, the code dy ...

Unable to locate the JSON file in the req.body after sending it through an HTTP post request

I have been working on implementing a new feature in my application that involves passing a JSON file from an Angular frontend to a Node backend using Express. The initial code reference can be found at How do I write a JSON object to file via Node server? ...

Issue with Angular: Unable to update model before modal closure on submit

I have a search form that is displayed within a modal window created using Angular UI Bootstrap. The input fields in the form update the ng-model when submitted. <script type="text/ng-template" id="mobileSearchPanel"> <form> ...

Error message: Vue warning - The prop "disabled" must be a boolean type, but a function was provided instead

I have this code snippet that I am currently using <v-list-item> <v-btn @click="onDownloadFile(document)" :disabled=getFileExtention >Download as pdf</v-btn > < ...

Tried to invoke the default export of the file located at C:UsersTeyllayDesktopss.lvfrontendsrcappapollo.ts on the server, but it is intended for the client-side

Question: I am facing an issue with querying user information when entering a specific user page like website/user/1. However, I keep encountering errors and suspect it might be related to Apollo. Is there a way to resolve this problem? What could I have d ...

Tips for implementing validation in JavaScript

I'm brand new to learning Javascript. Recently, I created a template for a login page and it's working perfectly fine. However, I am struggling with setting up validation and navigation. My goal is to redirect the user to another page if their us ...

Tips for avoiding unintended single clicks while double clicking in React

How can I make a function trigger on both single click and double click events when working with a video element in React? Currently, the single click function is also being called when double clicking. I am seeking a solution to this issue. Below is the ...

Clearing form data after submitting in Laravel using axiosIn Laravel, utilizing

When working on my Laravel app, I encountered an issue while submitting a form using Vue and Axios. Despite my attempts to clear the input field after submission, it doesn't seem to work. HTML: <form method="post" enctype="multipart/form-data" v- ...