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

90
Visualizações
Passing around array items in React

How do I fix the below code so that the state of Group A gets updated and rendered correctly? On click people from Group A should move to Group B. My hunch is something with useEffect, but I can't think of a way to implement this as aCopy only exists within the click handler.

code:

import React, { useEffect, useState } from "react";

export default function Test() {
  const [a, SetA] = useState(["Adam", "Brett", "Cody"]);
  const [b, SetB] = useState(["Donald", "Eric", "Fred"]);

  function click() {
    const aCopy = a;
    const mover = aCopy.pop();
    SetA(aCopy);
    SetB((prev) => [...prev, mover]);
  }

  return (
    <>
      <div>Group A: {a}</div>
      <div>Group B: {b}</div>
      <button onClick={click}>Click</button>
    </>
  );
}```
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use the Array.prototype.filter() method to filter the clicked item to remove it from one group while using the spread operator(...) to add it to the other group.

  const handleClickA = (item) => {
    SetA((prevA) => prevA.filter((o) => o !== item));
    SetB((prevB) => [...prevB, item]);
  };

This would work as you want. It can move items in between the groups as you expect.

handleClickA and handleClickB are almost same. You can reduce this to a single function if the information about the group is also available for each item.

function Test() {
  const [a, SetA] = React.useState(["Adam", "Brett", "Cody"]);
  const [b, SetB] = React.useState(["Donald", "Eric", "Fred"]);

  const handleClickA = (item) => {
    SetA((prevA) => prevA.filter((o) => o !== item));
    SetB((prevB) => [...prevB, item]);
  };

  const handleClickB = (item) => {
    SetB((prevB) => prevB.filter((o) => o !== item));
    SetA((prevA) => [...prevA, item]);
  };

  return (
    <div>
      <div>
        Group A:{" "}
        {a.map((itemA, indexA) => (
          <button key={indexA} onClick={() => handleClickA(itemA)}>
            {itemA}
          </button>
        ))}
      </div>
      <div>
        Group B:{" "}
        {b.map((itemB, indexB) => (
          <button key={indexB} onClick={() => handleClickB(itemB)}>
            {itemB}
          </button>
        ))}
      </div>
    </div>
  );
}

ReactDOM.render(<Test />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></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