Home > Software engineering >  How to move a button from one div to another when clicked in reactjs?
How to move a button from one div to another when clicked in reactjs?

Time:12-26

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?

CodePudding user response:

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>

  • Related