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.

function getRandomNumber() {
    let min = 1000;
    let max = 9999;
    return Math.round(Math.random() * (max - min) + min);

getRandomNumber(); // 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

  1. take an example of a number state which can store a random number
  2. create a function that generates 4 digits random number
  3. call the function with the click of a button
  4. print the output of the string on the page screen
import React, { useState, useEffect } from "react";
export default function App() {
    const [sampleNumber, setSampleNumber] = useState(null);

    const getRandomNumber = () => {
        let min = 1000;
        let max = 9999;
        setSampleNumber(Math.round(Math.random() * (max - min) + min))

  return (
    <div className="App">
      <h1>{`Genrate random number on click of the button`}</h1>
      <button onClick={() => getRandomNumber()}>{'Genrate'}</button>

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 👍.