function bgChanger() {
const [color, setColor] = useState('white');
const changeColor = () => {
const colors = ['red', 'lightblue','green', 'pink', 'violet', 'yellow', 'orange', 'torquoise']
var Scolor = colors[Math.floor(Math.random() * colors.length)];
setColor(Scolor);
}
I’m a beginner in React and this is my 2nd project.
I wanted to make a random color changer using react so i used an array to store the colors.
Used a variable Scolor (Select Color) which stores the randomized color from the array. But I didnt quite understand the how to do it, so I just copied a code snippet from Stackoverflow.
But now I’m unable to understand the code and I need assistance to understand why do we use Math.floor & multitply length of colors array with Math.Random
2
Answers
Math.random() return random value less then 1. like 0.2154, 0.6524.to display different color firstly i need a random number which should not greater then colors length. if i multiply Math.random() with colors length i will always get a number which is smaller then colors length. here is working code –
Math.floor() in typescript return the rounded number to the nearest down integer.
for example 4.89411570149498 once called the Math.floor() it will return
number: 4
You can check this code with the console.logs for the better understanding.
And Math.random() will generate a number like this: 0.8990969814246639