How to Create a Coin Flipping App using ReactJS?

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 logics. 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 update 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.

  • 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 single FlipCoin component only

    Javascript

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  • FlipCoin.js:  It contains all the behind the 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

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import React,{ Component } from 'react'
    import Coin from './Coin'
      
    class FlipCoin extends Component{
      static defaultProps = {
        coins : [
          // Sides of the coin
          {side:'head', imgSrc:
          {side:'tail', imgSrc:
        ]
      }
      
      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 intractions
      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

    chevron_right

    
    

  • 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

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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

    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.