To choose items randomly every 2 seconds from an array of numbers using ReactJS functional component, you can use the useState hook to keep track of the current randomly selected item and useEffect hook to update it every 2 seconds.
Here is an example code snippet:
import React, { useState, useEffect } from "react";
function RandomNumberSelector({ numbers }) {
const [selectedNumber, setSelectedNumber] = useState(null);
useEffect(() => {
const intervalId = setInterval(() => {
const randomIndex = Math.floor(Math.random() * numbers.length);
setSelectedNumber(numbers[randomIndex]);
}, 2000);
return () => clearInterval(intervalId);
}, [numbers]);
return (
<div>
<h2>Selected number: {selectedNumber}</h2>
</div>
);
}
export default RandomNumberSelector;
In this example, we create a functional component RandomNumberSelector that takes an array of numbers
as a prop. Inside the component, we use the useState hook to keep track of the current randomly selected number, which is initially set to null.
We also use the useEffect hook to set up a timer that updates the selected number every 2 seconds. Inside the useEffect hook, we use the setInterval
function to call a callback function every 2 seconds. In the callback function, we generate a random index based on the length of the numbers array and use it to select a random number from the array. We then update the selected number using the setSelectedNumber function.
Finally, we render the selected number in a heading element in the component's JSX.
Note that we pass the numbers array as a dependency to the useEffect hook to ensure that the timer is reinitialized whenever the array changes.
How to select many items randomly
Here is an example code snippet that demonstrates how to randomly choose 3 numbers from an array of 5 numbers every 2 seconds using ReactJS:
import React, { useState, useEffect } from "react";
const RandomNumbers = () => {
const [numbers, setNumbers] = useState([]);
const arr = [1, 2, 3, 4, 5];
useEffect(() => {
const interval = setInterval(() => {
const randomNumbers = [];
while (randomNumbers.length < 3) {
const index = Math.floor(Math.random() * arr.length);
const number = arr[index];
if (!randomNumbers.includes(number)) {
randomNumbers.push(number);
}
}
setNumbers(randomNumbers);
}, 2000);
return () => clearInterval(interval);
}, []);
return (
<div>
<p>Random Numbers:</p>
<ul>
{numbers.map((number) => (
<li key={number}>{number}</li>
))}
</ul>
</div>
);
};
export default RandomNumbers;
Here, we use the useState hook to store the randomly chosen numbers and the useEffect hook to set up an interval that runs every 2 seconds. Within the interval, we use a while loop to randomly choose 3 unique numbers from the arr array
and set them using the setNumbers function. Finally, we render the randomly chosen numbers in a list.