How to create a Dice Rolling App using ReactJS ?

Suppose there are two dice and a button to roll the dices. As we click the button both dices shake and generate a new number that shows on the upper face of the dices(in doted form as a standard dice). The numbers show on the upper face generates randomly each time we roll the dice.

There are two components Die and RollDice. The Die component is responsible to show one individual Dice. It is a stateless component. It uses the font-awesome library to show the standard dots on the upper face of the dice. RollDice component contains all the logic to generates random numbers to show on the upper face of the dice, roll each dice upon click on the roll button. There are two states involve in the RollDice component named ‘die1’ and ‘die2’. Each one has initialized with the value one i.e. each die shows one(one dot) when the application first starts. 

Now, we set the click event handler to the roll dice button and when anyone clicks on the button we change the state of both die1 and die2 to some random number using setState from one to six (we use a number as a word since font-awesome library deals with word number to show the exact number of dots). We also make sure when the dice is rolling user can’t click on the button again. For this purpose we use a state ‘rolling’ initially set to false and when the dice are rolling set rolling to true and start a timer of one second. After one second again set rolling state to false’. Disable the button when a rolling state is set to true.

This is a rough overview of the application. Let’s implement it to understand it better.

Example:



  • index.js:

    Javascript

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
      
    ReactDOM.render(<App />, document.querySelector('#root'))

    chevron_right

    
    

  • App.js: App component  renders a single RollDice component only

    Javascript

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import React from 'react';
    import RollDice from './RollDice'
      
    function App() {
      return (
        <div>
          <RollDice />
        </div>
      );
    }
      
    export default App;

    chevron_right

    
    

  • RollDice.js : It contains all the behind the logic. The setting event handler, updating all the states according to the user’s interaction render Die component. This file has to be created by you.

    Javascript

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import React,{ Component } from 'react'
    import './RollDice.css'
    import Die from './Die'
      
    class RollDice extends Component{
      
      // Face numbers passes as default props
      static defaultProps = {
        sides : ['one', 'two', 'three'
                 'four', 'five', 'six']
      }
      constructor(props){
        super(props)
          
        // States
        this.state = {
          die1 : 'one',
          die2 : 'one',
          rolling: false
        }
        this.roll = this.roll.bind(this)
      }
      roll(){
        const {sides} = this.props
        this.setState({
          
          // Changing state upon click
          die1 : sides[Math.floor(Math.random() * sides.length)],
          die2 : sides[Math.floor(Math.random() * sides.length)],
          rolling:true
        })
          
        // Start timer of one sec when rolling start
        setTimeout(() => {
          
          // Set rolling to false again when time over
          this.setState({rolling:false})
        },1000)
      }
      
      render(){
        const handleBtn = this.state.rolling ? 
                          'RollDice-rolling' : ''
        const {die1, die2, rolling} = this.state
        return(
          <div className='RollDice'>
            <div className='RollDice-container'>
              <Die face={die1} rolling={rolling}/>
              <Die face={die2} rolling={rolling}/>
            </div>
            <button className={handleBtn}
                    disabled={this.state.rolling} 
                    onClick={this.roll}>
              {this.state.rolling ? 'Rolling' : 'Roll Dice!'}
            </button>
          </div>
        )
      }
    }
      
    export default RollDice

    chevron_right

    
    

  • Die.js: Responsible to show single-die component only with correct doted number face as communicated by the parent RollDice component. This file has to be created by you.

    Javascript



    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import React, {Component} from 'react'
    import './Die.css'
      
    class Die extends Component{
      render(){
        const {face, rolling} = this.props
          
        // Using font awesome icon to show 
        // the exactnumber of dots
        return <i className={`Die fas fa-dice-${face}
                  ${rolling && 'Die-shaking'}`}/>
      }
    }
      
    export default Die

    chevron_right

    
    

  • RollDice.css : Styling RollDice component contents

    CSS

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    .RollDice{
      display: flex;
      flex-flow: column nowrap;
      min-height: 100vh;
    }
      
    /* Shows each dice in one row */
    .RollDice-container{
      display: flex;
      justify-content: center;
      align-content: center;
    }
    /* Stylling rolldice button */
    .RollDice button{
      width:15em;
      padding:1.5em;
      border: 0px;
      border-radius: 10px;
      color:white;
      background-color:black;
      margin-top: 3em;
      align-self: center;
    }
      
    /* Setting hover effect on button */
    .RollDice button:hover{
      cursor: pointer;
    }
      
    .RollDice-rolling{
      border: 0px;
      border-radius: 10px;
      background-color:darkslateblue !important;
      opacity:0.7
    }

    chevron_right

    
    

  • Die.css: Styling each die component and setting animation effect to it.

    CSS

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    /* Styling each Die */
    .Die{
      font-size:10em;
      padding:0.25em;
      color:slateblue;
    }
      
    /* Applying Animation */
    .Die-shaking{
      animation-name:wobble;
      animation-duration: 1s;
    }
      
    /* Setting Animation effect to the 
       dice using css keyframe */
    @keyframes wobble {
      from {
        transform: translate3d(0, 0, 0);
      }
      15% {
        transform: translate3d(-25%, 0, 0
                   rotate3d(0, 0, 1, -5deg);
      }
      30% {
        transform: translate3d(20%, 0, 0
                   rotate3d(0, 0, 1, 3deg);
      }
      45% {
        transform: translate3d(-15%, 0, 0)
                   rotate3d(0, 0, 1, -3deg);
      }
      60% {
        transform: translate3d(10%, 0, 0
                   rotate3d(0, 0, 1, 2deg);
      }
      75% {
        transform: translate3d(-5%, 0, 0
                   rotate3d(0, 0, 1, -1deg);
      }
      to {
        transform: translate3d(0, 0, 0);
      }
    }

    chevron_right

    
    

Output :

react-js-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.