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

203
Vistas
How to move a button from one div to another when clicked in reactjs?

I've placed the following buttons within a div

const [state, setstate] = useState([]);

getButtonsUsingMap(){
const arr = [1,2,3,4,5];  
return arr.map((num) => {
    return (
        <button
            key={num}
            className="buttons"
            onClick={(e) => {
                state.push(num);
            }}
        >
            {num}
        </button>
    );
});
}

Currently my two divs look like this:

function App(){
return (
    <>
      <div className="left" style={{ float: "left" }}>
        {getButtonsUsingMap()}
      </div>
      <div className="right" style={{ float: "right" }}></div>
    </>
  );
}

When those buttons are clicked, I want them to move to another div. And when the button is clicked on the other div, the button has to come back to the original div.I found a solution but it involves document.getElementById(). But I believe that it is not a good thing to do in reactjs. Any ideas?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Set up a state which can contain the numbers, and add data ids to the divs. Then in your click handler you can pick out the button number and the div id, and then reset the state.

const { useState } = React;

function Example() {

  const [ data, setData ] = useState({
    divOne: [1, 2 , 3, 4, 5],
    divTwo: []
  });

  function handleClick(e) {
    const { parentNode, nodeName } = e.target;

    if (nodeName === 'BUTTON') {
      const { num } = e.target.dataset;
      const { id } = parentNode.dataset;
      const remaining = data[id].filter(el => el !== +num);
      if (id === 'divOne') {
        setData({
          divOne: remaining,
          divTwo: [...data.divTwo, +num].sort()
        });
      }
      if (id === 'divTwo') {
        setData({
          divOne: [...data.divOne, +num].sort(),
          divTwo: remaining
        });
      }
    }
  }

  return (
    <div onClick={handleClick}>
      <div data-id="divOne" className="red">
        {data.divOne.map(el => {
          return (
            <button data-num={el}>
              Click {el}
            </button>
          )
        })}
      </div>
      <div data-id="divTwo" className="blue">
        {data.divTwo.map(el => {
          return (
            <button data-num={el}>
              Click {el}
            </button>
          )
        })}
      </div>
    </div>
  );

};

const arr = [1, 2, 3, 4, 5];

ReactDOM.render(
  <Example arr={arr} />,
  document.getElementById('react')
);
div { padding: 1em; }
.blue { background-color: blue; }
.red { background-color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Santiago Trujillo 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