JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Generate a random number in React

Author:JIYIK Last Updated:2025/03/16 Views:

Use Math.random()the function to generate a random number in React, for example Math.floor(Math.random() * (max - min + 1)) + min. Math.randomThe function returns a number in the range of 0 to less than 1, but can also be used to generate numbers in a specific range.

import {useState} from 'react';

const App = () => {
  const [num, setNum] = useState(0);

  function randomNumberInRange(min, max) {
    // 👇️ 获取 min(含)和 max(含)之间的数字
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  const handleClick = () => {
    setNum(randomNumberInRange(1, 5));
  };

  return (
    <div>
      <h2>number is: {num}</h2>
      <button onClick={handleClick}>Generate random number</button>
    </div>
  );
};

export default App;

The code snippet above uses the Math.random() function to generate numbers in the range 1 (inclusive) to 5 (inclusive).

React generates random numbers

If you do not need to generate numbers within a specific range, but just need a random number, you can use Math.random()the function directly.

console.log(Math.random()); // 👉️ 0.9349907593750104
console.log(Math.random()); // 👉️ 0.1028502928025743
console.log(Math.random()); // 👉️ 0.9268013352071363

If we need to generate a random number every N seconds and render in a component, use the useEffect hook to set the interval.

import {useEffect, useState} from 'react';

const App = () => {
  const [num, setNum] = useState(0);

  function randomNumberInRange(min, max) {
    // 👇️ 获取 min(含)和 max(含)之间的数字
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  useEffect(() => {
    const interval = setInterval(() => {
      // 👇️ 生成 1 到 10 之间的随机数
      setNum(randomNumberInRange(1, 10));
    }, 1000); // 👈️ 每秒执行一次

    return () => {
      clearInterval(interval);
    };
  }, []);

  return (
    <div>
      <h2>number is: {num}</h2>
    </div>
  );
};

export default App;

The example above uses setInterval()the method to call a function every 1 second.

The second parameter we pass to the setInterval() method is the delay in milliseconds between function calls. If you don’t pass a delay parameter, it defaults to 0.

In the function, we generate a random number between 1 and 10 and update the state variable.

The function we useEffectreturn from the hook is run when the component unmounts.

We use clearInterval()the method to cancel the repeating action we set up using setInterval .

This is what we should always do when using methods like setInterval()or addEventListener(), because if we don't clean up when a component is unmounted, our application will have memory leaks.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:185 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:183 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:99 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:58 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:187 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Solve the Module not found: Can't resolve 'react-bootstrap' error

Publish Date:2025/03/16 Views:85 Category:React

To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial