Home > Software engineering >  How to add class to selected element in React Js
How to add class to selected element in React Js

Time:06-20

I have numbers in my list and I am displaying them on the board:

const numbers = [
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
    22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
    60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75,
  ];
{numbers.map(number, index) => (
            <div className="bingo-grid__row" id={index 1} key={index}>
                <div className={className}>
                  <div className="bingo-ball bingo-ball">
                    <div className="bingo-ball__text">{number}</div>
                  </div>
                </div>
              </div>
          )
}

Besides that, I am selecting a random number:

const [chosen, setChosen] = useState(null);
  const [selectedNumbers, setSelectedNumbers] = useState([]);
  const chooseNumber = () => {
    let r;
    do {
      r = Math.floor(Math.random() * 75)   1;
    }
    while (selectedNumbers.indexOf(r) > -1)
    setChosen(r)
    setSelectedNumbers([...selectedNumbers, r]);
  };

And what I am trying to do is add a class if the number is matching with the random number. So for example, if the random number is 6, I want to add a new class to the bingo-grid__row. Any suggestion for this?

CodePudding user response:

You can create the class dynamically by adding a condition like this:

{numbers.map( (number, index) => (
  <div className={`bingo-grid__row ${chosen === number ? yourClassToAdd : ""}`} id={index 1} key={index}>
  //rest of the logic
 )
}

Update: If you want to keep the selections persistent then you can change the condition to use the selectedNumbers state that you already created like this:

{numbers.map( (number, index) => (
  <div className={`bingo-grid__row ${selectedNumbers.includes(number) ? yourClassToAdd : ""}`} id={index 1} key={index}>
  //rest of the logic
 )
}

CodePudding user response:

const [chosen, setChosen] = useState(null);
  const [selectedNumbers, setSelectedNumbers] = useState([]);
  const chooseNumber = async () => {
    let r;
    let component = document.querySelector(".bingo-grid__row")
    do {
      r = await Math.floor(Math.random() * 75)   1;
      if(r === 6){
      componet.classList.add("newClass")
      }
    }
    while (selectedNumbers.indexOf(r) > -1)
    setChosen(r)
    setSelectedNumbers([...selectedNumbers, r]);
  };
  • Related