Search code examples
reactjsreact-component

how to create random number with click event in react


I want to create random numbers from 1 to 50 when I click the button. So here is my component for this:

import React from 'react'
import './Board.css';

const Board = () => {
    let rand;
    function createNumber() {
        rand = Math.floor(Math.random() * 50) + 1;
    }
    return (
        <div className="game-board">
            <div id="selected-number">
                <h1 className="bingo-ball__text">{rand}</h1>
                <button className="button button3" onClick={createNumber}>Select Number</button>
            </div>
        </div>
    )
}

export default Board

But when I click, I cannot get any response (so I dont see anything inside of this {rand}) or error.


Solution

  • You should use the react hook useState so that your component gets re-rendered when you generate a new random numer like so:

    import "./styles.css";
    import { useState } from "react";
    
    export default function App() {
      const [rnd, setRnd] = useState(0);
    
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <button onClick={() => setRnd(Math.floor(Math.random() * 50))}>
            gen randomn num
          </button>
          <div>{rnd}</div>
        </div>
      );
    }
    

    Example: https://codesandbox.io/s/black-pine-5sgxxw?file=/src/App.js:0-349