He colocado los siguientes botones dentro de un 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> ); }); }Actualmente mis dos divs se ven así:
function App(){ return ( <> <div className="left" style={{ float: "left" }}> {getButtonsUsingMap()} </div> <div className="right" style={{ float: "right" }}></div> </> ); }Cuando se hace clic en esos botones, quiero que se muevan a otro div. Y cuando se hace clic en el botón en el otro div, el botón debe volver al div original. Encontré una solución pero implica document.getElementById(). Pero creo que no es bueno hacerlo en reactjs. ¿Algunas ideas?
Configure un estado que pueda contener los números y agregue identificadores de datos a los divs. Luego, en su controlador de clics, puede seleccionar el número de botón y la identificación de división, y luego restablecer el estado.
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>