0

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.

2

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.