Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda