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 dice (in dotted form as a standard dice). The numbers shown 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 generate random numbers to show on the upper face of the dice, roll each dice upon click on the roll button. There are two states involved 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 the 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.
Please Login to comment...