skip to Main Content
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


  1. 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 –

    import { useState } from "react";
    
    const colors = [
      "red",
      "lightblue",
      "green",
      "pink",
      "violet",
      "yellow",
      "orange",
      "torquoise",
    ];
    const App = () => {
      const [color, setColor] = useState(colors[0]);
      
      const setRandomColor = () => {
        setColor(colors[Math.floor(Math.random() * colors.length)]);
      };
    
      return (
        <div style={{ backgroundColor: color, height: "100vh", width: "100vw" }}>
          <button onClick={setRandomColor}>Change Color</button>
        </div>
      );
    };
    
    export default App;
    
    Login or Signup to reply.
  2. 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.

    const changeColor = () => { 
      const colors = ['red', 'lightblue','green', 'pink', 'violet', 'yellow', 'orange', 'torquoise'] 
      const tt = Math.random() * 7
      console.log(tt)
      console.log(Math.floor(tt))
      var Scolor = colors[Math.floor(Math.random() * colors.length)]; 
      console.log(Scolor)
    }
    
    changeColor()
    

    And Math.random() will generate a number like this: 0.8990969814246639

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search