How to Create a Coin Flipping App using ReactJS? - GeeksforGeeks

07 Jul, 2021

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- index.js:
Javascript
 

 
 










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






Filename- App.js: App component renders single FlipCoin component only 
Javascript
 

 
 










import React from 'react';
import FlipCoin from './FlipCoin'
 
const App=()=> {
  return (
    <div className="App">
      <FlipCoin />
    </div>
  );
}
 
export default App;






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.
Javascript
 

 
 










import React,{ Component } from 'react'
import Coin from './Coin'
 
class FlipCoin extends Component{
  static defaultProps = {
    coins : [
     
      // Sides of the coin
      {side:'head', imgSrc:
'https://media.geeksforgeeks.org/wp-content/uploads/20200916123059/SHalfDollarObverse2016head-300x300.jpg'},
      {side:'tail', imgSrc:
'https://media.geeksforgeeks.org/wp-content/uploads/20200916123125/tails-200x200.jpg'}
    ]
  }
 
  constructor(props){
    super(props)
     
    // Responsible to render current updated coin face
    this.state = {
       
      // Track total number of flips
      currFace : null,
      totalFlips:0,
      heads: 0
    }
     
    // Binding context of this keyword
    this.handleClick = this.handleClick.bind(this)
  }
 
   // Function takes array of different faces of a coin
  //  and return a random chosen single face
  choice(arr){
    const randomIdx = Math.floor(Math.random() * arr.length)
    return arr[randomIdx]
  }
   
  // Function responsible to update the states
  // according to users interactions
  flipCoin(){
    const newFace = this.choice(this.props.coins)
    this.setState(curState => {
      const heads = curState.heads + 
      (newFace.side === 'head' ? 1 : 0)
      return {
        currFace:newFace,
        totalFlips:curState.totalFlips + 1,
        heads:heads
      }
    })
  }
 
  handleClick(){
    this.flipCoin()
  }
  render(){
    const {currFace, totalFlips, heads} = this.state
    return(
      <div>
        <h2>Let's flip a coin</h2>
         
        {/* If current face exist then show current face */}
        {currFace && <Coin info={currFace} />}
         
        {/* Button to flip the coin  */}
        <button onClick={this.handleClick}>Flip Me!</button>
         
         
 
<p>
          Out of {totalFlips} flips, there have been {heads} heads 
          and {totalFlips - heads} tails
        </p>
 
 
 
      </div>
    )
  }
}
 
export default FlipCoin






 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
Javascript
 

 
 










import React,{ Component } from 'react'
 
class Coin extends Component{
  render(){
    return(
      <div class='Coin'>
        <img
          style={{ width:'200px', height:'200px' }}
          src={this.props.info.imgSrc} 
        />
      </div>
    )
  }
}
 
export default Coin






  Output :
shubhamyadav4
varshagumber28

react-js


Web Technologies

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?
How to calculate the number of days between two dates in javascript?