Home > Software design >  How to dynamically add and remove mapped array to another array when clicked and remove from arr whe
How to dynamically add and remove mapped array to another array when clicked and remove from arr whe

Time:09-26

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>
      );
    }

CodePudding user response:

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>

CodePudding user response:

/* 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>
      );
    }

  
  • Related