Hi Friends 👋,
Welcome To Infinitbility! ❤️
To generate a random number in react js, use the Math.random()
method it will generate a random number.
In the following example, we set the min and max number with the Math.random()
method so it will generate random numbers in the range of min and max number.
1function getRandomNumber() {2 let min = 1000;3 let max = 9999;4 return Math.round(Math.random() * (max - min) + min);5}67getRandomNumber(); // return 4 char random number
Today, I’m going to show you How do i generate random numbers in react js, as mentioned above here, I’m going to use the Math.random()
method.
Let’s start today’s tutorial how do you generate random numbers in react js?
In this example, we will do
- take an example of a number state which can store a random number
- create a function that generates 4 digits random number
- call the function with the click of a button
- print the output of the string on the page screen
1import React, { useState, useEffect } from "react";2export default function App() {3 const [sampleNumber, setSampleNumber] = useState(null);45 const getRandomNumber = () => {6 let min = 1000;7 let max = 9999;8 setSampleNumber(Math.round(Math.random() * (max - min) + min))9 }1011 return (12 <div className="App">13 <h1>{`Genrate random number on click of the button`}</h1>14 <button onClick={() => getRandomNumber()}>{'Genrate'}</button>15 <p>{sampleNumber}</p>16 </div>17 );18}
In the above react js example, we have taken the sample number state, and create a function which can genrate random number with in range and store in the state.
I hope it helps you, All the best 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.