Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
ReactJS: Detect which button is clicked

I have this simple requirement that detects which button is clicked. The code is as below:

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>
    </div>
  )
}

export default App

The code above will display text as below:

Hotel 1A      Hotel 1B
A             B

If I click on Hotel 1A, I have like 'A' to be changed to 'C' and if I click on Hotel 1B, only 'B' will change to 'C'. I thought I need to get the value of the button but I could not get it to work.

Any help would be greatly appreciated.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

  • First, you are assigning item[index] to item[e.target.value] in if check , change = too ===
  • Second, you have one state for both buttons, you have to keep 1 value for each button

if you just want to make that code work here is an working example:

const [sameText, setSameText] = useState([false, false]);

  const changeText = (e: any, index: number, item: any) => {
    if (item[e.target.value] === item[index]) {
      const newState = [...sameText];
      newState[index] = true;
      setSameText(newState);
    }
  };

and if check

<div>{sameText[index] ? 'C' : item[1][0]}<div/>

For N hotels you can use that:

const [clickedHotel, setClickedHotel] = useState(
    null,
  );

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

and

<div>{clickedHotel === index ? 'C' : item[1][0]}</div>
about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to store the state for each button and change the state on click. Your buttons are rendered based on the button state

For example:

  1. introduce const [buttonState, setButtonState] = useState(data);
  2. map over buttonState instead of data
  3. in changeText() change the state as you want by calling setButtonState()
about 4 years ago · Juan Pablo Isaza Denunciar

0

You are using the nested arrays in the items array

You are almost there and you have done it correctly console.log(item[1][0]) will give you the

But there is one more thing you need to do is following:

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(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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda