Issue
I am trying to convert the js project to react and I need to add a class to a random circle and flash it using calling the same function again but I don't know how to convert this two line of code into react: circles[nextActiveNum].classList.toggle("active"); circles[activeNum].classList.remove("active"); I have made a circle component in react for that and all the state is in a class component.
const startButton = document.querySelector("#start");
const endButton = document.querySelector("#end");
const circles = document.querySelectorAll(".circle");
let count = 0;
let activeNum = 0;
let timer;
let pace = 1000;
let rounds = 0;
let gameIsOn = false;
//sounds
const startSound = new Audio("sounds/starter.wav");
const endGameSound = new Audio("sounds/gameover.wav");
const click = new Audio("sounds/click.wav");
console.log(startSound);
// start game functionality starts here
const playAudio = () => {
startSound.play();
};
const randomNumber = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
const newCircle = (activeNum) => {
let nextActiveNum = randomNumber(0, 3);
if (activeNum != nextActiveNum) {
return nextActiveNum;
} else {
return newCircle(activeNum);
}
};
const startgame = () => {
gameIsOn = true;
startButton.style.display = "none";
endButton.style.display = "initial";
let nextActiveNum = newCircle(activeNum);
circles[nextActiveNum].classList.toggle("active");
circles[activeNum].classList.remove("active");
activeNum = nextActiveNum;
timer = setTimeout(startgame, pace);
pace -= 10;
rounds++;
if (rounds >= 2) {
return endGame();
}
};
Solution
You could do something like this:
Circle component
const Circle = ({ active }) => {
const classList = ['circle'];
if (active) classList.push('active');
return <div className={classList.join(' ')}></div>;
};
Parent component
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const circles = new Array(4).fill(Circle);
export default function App() {
const [activeNum, setActiveNum] = useState(null);
function nextNum() {
setActiveNum((prev) => {
let next = prev;
while (next === prev) next = randomNumber(0, 3);
return next;
});
}
return (
<div>
{circles.map((C, i) => (
<C active={i === activeNum} />
))}
<br />
<button onClick={nextNum}>Next</button>
</div>
);
}
https://stackblitz.com/edit/react-ts-fwn9xc?file=App.tsx
Let me know if something is unclear.
Answered By - Chris Hamilton
Answer Checked By - - Robin (ReactFix Admin)