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

94
Vistas
How to dynamically add and remove mapped array to another array when clicked and remove from arr when clicked again in reactjs

I'm working on a project where I mapped through a lisf of numbers from 1 to 90 and returned a button for each number, so when I click a particular button the color changes and when I click again the color goes away. So here is my problem I need to add the number in that button to a list when the button is clicked and and the color changes then remove it from the list when the button is clicked again and the color changes back to normal. This the codebase of what I did to add colors to the button when clicked and remove color when clicked again.

    import React from 'react';
    import './style.css'; 
    export default function App() {
      const [activeNums, setActiveNums] = React.useState({});
        let nums = []
        for (let i = 1; i < 91; i++) {
            nums.push(i)
        }
      const onToggle = (num) => {
        setActiveNums((state) => {
          return {
            ...state,
            [num]: !state[num],
          };
        });
      };
      return (
        <div>
          {nums.map(i => {
              return <button key={i} name={!activeNums[i] && 'ready'} onClick={(e) => 
              handleClass(i, e)} className={`${activeNums[i] ? 'game_clicked' : ''} 
              game_btn `}>{i}</button>
          })}
        </div>
      );
    }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

So as I understand you want to have buttons, which you click/unclick and adding button number to some object. Can be done like this:

// import React from "react";

const App = () => {
  const [activeNums, setActiveNums] = React.useState({});

  const buttonHandler = ({ target: { name } }) => {    
    setActiveNums({ ...activeNums, [name]: !activeNums[name] });
  };

  return (
    <div>
      {[...Array(10)].map((_, idx) => {
        const number = idx + 1;
        return (
          <button key={number} name={number} onClick={buttonHandler}>
            My number is: {number} <br />I am{" "}
            {activeNums["" + number] ? "" : "not"} ready.
          </button>
        );
      })}
      <div>{JSON.stringify(activeNums)}</div>
    </div>
  );
};

// export default App;

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

/* I think this is what you were going for, hope this helps - */

    import React from "react";
    import "./styles.css";
    
    export default function App() {
      const [activeNums, setActiveNums] = React.useState([]);
      let nums = [];
      for (let i = 1; i < 91; i++) {
        nums.push(i);
      }
    
      const onToggle = (num) => {
        setActiveNums((prevState) => {
          if (prevState.includes(num)) {
            return [...prevState.filter((n) => n !== num)];
          } else {
            return [...prevState, num];
          }
        });
      };
    
      return (
        <div>
          {nums.map((num) => {
            return (
              <button
                key={num}
                onClick={(e) => onToggle(num)}
                className={activeNums.includes(num) ? "game_clicked" : ""}
              >
                {num}
              </button>
            );
          })}
        </div>
      );
    }

  
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