Created
September 15, 2020 10:01
-
-
Save dearshrewdwit/885d4df8cbeaa4f7a32d053a6b7db1dc to your computer and use it in GitHub Desktop.
Comparing Class and Functional components in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// DiceRoll.js | |
import React, { Component } from 'react' | |
import Die from './Die' | |
class DiceRoll extends Component { | |
constructor(props) { | |
super(props) | |
this.state = {dice: [4,5,6]} | |
} | |
roll = () => { | |
const randomDice = this.state.dice.map((die) => { | |
return this._getRndInteger(1, 6) | |
}) | |
this.setState({dice: randomDice}) | |
} | |
_getRndInteger(min, max) { | |
return Math.floor(Math.random() * (max - min + 1) ) + min; | |
} | |
render() { | |
return( | |
<div className="dice-roll"> | |
<button onClick={this.roll}>Roll</button> | |
{this.state.dice.map((die, index) => { | |
return ( | |
<Die number={die} key={index} /> | |
) | |
})} | |
</div> | |
) | |
} | |
} | |
export default DiceRoll | |
// Die.js | |
import React from 'react' | |
function Die(props) { | |
return ( | |
<div className="die"> | |
{props.number} | |
</div> | |
) | |
} | |
export default Die |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment