React Projects

Create a Dice Game with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a dice game with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app dice-game

with NPM to create our React project.

Create the Dice Game

To create the dice game, we write:

import React, { useState } from "react";

export default function App() {
  const [rolledValue, setRolledValue] = useState(1);

  const roll = () => {
    setRolledValue(Math.ceil(Math.random() * 5 + 1));

  return (
      <button onClick={roll}>roll</button>
      <p>rolled dice value: {rolledValue}</p>

We have the rolledValue state that has the rolled dice’s value.

Then we create the roll function to set the rolledValue state to a random number.

Since Math.random only return a number between 0 and 1, we’ve to multiply the returned value by 5 and add 1 to generate a random number between 1 and 6.

Below that, we have a button that calls roll when we click it.

And we show the rolledValue below that.


We can create a dice game easily with React and JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *