Basically, we want to build an app to toss or flip the coin. each time coin is flipped randomly a side of a coin is shown from head and tail and also we want to keep track of how many times coins are flipped and how many times heads and tails appear from those.
We create three components ‘App’ and ‘FlipCoin’ and ‘Coin’. The app component renders a single FlipCoin component only. There is no actual logic put inside the App component. FlipCoin component contains all the behind the logic. It has a default prop coin that is an array that contains two images head and tail (sides of a coin). It is a stateful component and has three states’ current faces, the total number of flips, and the number of heads. A click event handler is set to the button ‘flip’. The handler function basically chooses face head or tail randomly based on a randomly generated value and updates the current face state from the chosen face each time handler runs. The handler function also keeps track of how many times the flip button is clicked and how many times the head face generated randomly and updates its value to the respective state. The last Coin component is responsible for showing the correct coin face according to the randomly chosen side from the handler function in the FlipCoin component. FlipCoin uses a props system to communicate with the Coin component.
Example: In this example, we will make a few changes on App.js, to import a component. In that component, we will include two sides of a coin of an image. And flip that as a single image.
Filename- App.js: App component renders single FlipCoin component only
Filename- FlipCoin.js: It contains all the behind logic. It is a stateful component. The states are currFace, totalFlips, and heads. It contains two sides of a coin as a default prop and updates the currFace state according to a random number that generates each time the component re-render. It is responsible for Setting event handler, updating all the states according to the user interaction render Coin component.
Filename- Coin.js: Responsible to show a side of a coin according to the currFace state of FlipCoin component. FlipCoin component communicates with the Coin component through the props system