Determining the Clicked Button in ReactJS

I need help with a simple coding requirement that involves detecting which button is clicked. Below is the code snippet:

import React, { useState } from 'react'

const App = () => {
  const data = [
    ['Hotel 1A', ['A']],
    ['Hotel 1B', ['B']],
  ]

  const [sameText, setSameText] = useState(false)

  const changeText = (e: any, index: number, item: any) => {
    console.log(e.target.value)
    console.log(index)
    console.log(item)

    if ((item[e.target.value] == item[index])) {
      setSameText(true)
    }
  }
  return (
    <div className='mx-auto'>
      <div className='flex p-16'>
        {data.map((item, index) => (
          <div className='mx-16' key={index}>
            <div className='p-12'>
              <button onClick={(e) => changeText(e, index, item)} value={index}>
                {item[0]}
              </button>
              <div>{sameText ? 'C' : item[1][0]}</div>
            </div>
          </div>
        ))}
      </div>
    </dev>
  )
}

export default App

The provided code will output text as follows:

Hotel 1A      Hotel 1B
A             B

If I click on Hotel 1A, I want 'A' to be changed to 'C,' and if I click on Hotel 1B, only 'B' should change to 'C.' Despite my efforts to retrieve the button's value, I couldn't make it work.

Any assistance would be highly appreciated.

Answer №1

  • Firstly, make sure you are using item[index] instead of item[e.target.value] in the if statement and change the assignment operator from = to ===
  • Secondly, it is important to maintain separate states for each button instead of one shared state

If you need a working example, here is some code:

const [isTextMatching, setIsTextMatching] = useState([false, false]);

  const checkText = (e: any, index: number, item: any) => {
    if (item[e.target.value] === item[index]) {
      const newState = [...isTextMatching];
      newState[index] = true;
      setIsTextMatching(newState);
    }
  };

For multiple hotels, you can use:

const [selectedHotel, setSelectedHotel] = useState(null);

  const checkText = (e: any, index: number, item: any) => {
    if (item[e.target.value] === item[index]) {
      setSelectedHotel(index);
    }
  };

Answer №2

To effectively manage the state of each button and update it upon click, you will need to implement a mechanism where the buttons are displayed based on their current state.

Here is an example solution:

  1. Create a state variable using
    const [buttonState, setButtonState] = useState(data);
  2. Iterate through buttonState instead of data when rendering the buttons
  3. In the changeText() function, modify the button state as needed by invoking setButtonState()

Answer №3

You seem to be utilizing nested arrays within the items array.

You are very close to the desired outcome and have implemented it correctly; console.log(item[1][0]) will provide you with the result.

There is just one more step you need to take, which is outlined below:

import React, { useState } from 'react'

const App = () => {
  const data = [
    ['Hotel 1A', ['A']],
    ['Hotel 1B', ['B']],
  ]

  const [sameText, setSameText] = useState(false)

  const changeText = (e, index, item) => {
    console.log(item[1][0])

    // if ((item[e.target.value] = item[index])) {
    //   setSameText(true)
    // }
  }
  return (
    <div className='mx-auto'>
      <div className='flex p-16'>
        {data.map((item, index) => (
          <div className='mx-16' key={index}>
            <div className='p-12'>
              <button onClick={(e) => changeText(e, index, item)} value={index}>
                {item[0]}
              </button>
              <div>{sameText ? 'C' : item[1][0]}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

export default App

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 Vue.js component appears to be hidden within the Swal.fire HTML

Here is how I use Swal.Fire in my file1.js: import TextModuleComponent from "../components/TextModuleComponent"; export default { components: {TextModuleComponent} } Swal.fire({ title: 'Sending the offer via email?', ...

Switch up the blogs displayed depending on the category chosen using React

I seem to have hit a roadblock with my current issue. My challenge involves organizing and displaying blog posts according to their categories: const Posts = ({ state }) => { const data = state.source.get(state.router.link); const postsPerCategory ...

Step-by-step guide on programmatically closing the Material-UI DropDownMenu

http://www.material-ui.com/#/components/dropdown-menu Having encountered a styling issue, I was compelled to rearrange the order of components within my material-ui DropdownMenu. Nevertheless, some buttons (renderNavLink) are now failing to close the Dro ...

My jQuery form is not functioning properly upon initialization

Let's take a look at this sample 'template' code: $(document).on("<EVENT>", "form", function() { $(this).find(".input input").each(function() { var required = $(this).attr("required"); var checkField = $(this).clos ...

Creating a seamless navigation experience using Material UI's react Button and react-router-dom Link

Is there a way to have the Material UI react Button component behave like a Link component from react-router-dom while preserving its original style? Essentially, how can I change the route on click? import Button from '@material-ui/core/Button' ...

What is the best way to change the content in a textarea field?

I am looking to create a functionality where a div is displayed below selected text inside a textarea. Below is the JavaScript code: function getSel() { var txtarea = document.getElementById("mytextarea"); var start = txtarea.selectionStart; ...

Redirecting to a new page in JavaScript as the clock nears the top of the hour after 5 minutes

I am looking to automatically redirect a user to another page when it is 5 minutes until the start of the next hour. In military time (24-hour clock), this means I want the redirect to occur at times like... 11:55 12:55 13:55 14:55 15:55 etc So far, I ...

Initial binding of Angular2 ControlGroup valueChanges event

My form contains <input type="text"> elements and I've noticed that ControlGroup.valueChanges is triggered during initial data binding when using [ngFormModel] and ngControl. As a result, it gives the impression to the user that the form has al ...

What is causing all the React components to adjust their heights simultaneously instead of just one

I am creating a Trello-inspired application and I have a component that is rendered multiple times. Within this component, there is a button that, when clicked, should reveal an input field along with another button, resembling the design in this image: be ...

How can AngularJS apps handle authentication?

Seeking input on user authentication with AngularJS and Zend... I currently have Angular on the client side and Zend on the server side handling authentication successfully. However, I'm looking for best practices and code examples for enhancing the ...

Exploring the concept of kleisli composition in TypeScript by combining Promise monad with functional programming techniques using fp-ts

Is there a way to combine two kleisli arrows (functions) f: A -> Promise B and g: B -> Promise C into h: A -> Promise C using the library fp-ts? Having experience with Haskell, I would formulate it as: How can I achieve the equivalent of the > ...

Troubleshooting: Why isn't my React useState function merging two arrays as

Need Assistance with useState Hook const [pending, setPending] = useState([]); I have two separate locations where I am updating similar arrays. api.request('/api/director-user', 'GET') .then(res => { if (res.sta ...

Transforming the text to be "unreadable"

I find myself in a rather odd predicament where I must display my name and contact details on a webpage. Although I am comfortable with sharing this information, I would prefer that it remain unreadable to robots or other unauthorized sources. Essentially ...

What steps do I need to follow in Material-UI to establish a nonce for the Content-Security-Policy?

As someone working on a React App that utilizes Create-React-App and Material-UI, I am seeking to implement a strict Content-Security-Policy for my application that disallows unsafe inline styles. While it is simple to set the CSP-Header server-side with ...

The issue with ng-select arises when the placeholder option is selected, as it incorrectly sends "NULL" instead of an empty string

When searching for inventory, users have the option to refine their search using various criteria. If a user does not select any options, ng-select interprets this as "NULL," which causes an issue because the server expects an empty string in the GET reque ...

Angular Bootstrap UI - Ensuring only one element collapses at a time

I have integrated the angular bootstrap UI library into my website by following this link: https://angular-ui.github.io/bootstrap/ One issue I am facing is that when I implement a collapsible feature using this library, it collapses or expands every eleme ...

ng-click is not triggering my function

I'm really struggling to understand how AngularJS and Typescript can work together efficiently. My main goal is to make a simple method call, but I seem to be stuck due to some constraints in the architecture I have chosen. I must have made a mistake ...

Prevent key input in Material UI TextField

Is there a way to restrict users from manually inputting values into my Material UI TextField and instead, direct them to use the number stepper? I've attempted a solution without success. import React, { useState } from "react"; import Reac ...

Leveraging split and map functions within JSX code

const array = ['name', 'contact number'] const Application = () => ( <div style={styles}> Unable to display Add name & contact, encountering issues with splitting the array). </div> ); I'm facing difficul ...

"Exploring the use of conditional rendering in React to dynamically hide and show components based

I am currently immersed in the world of React/Redux, focusing on an e-commerce project. This particular application offers two payment methods: cash and card payments. On the product display page, both payment icons are visible. However, I am seeking a sol ...