import React, { Component } from 'react';
import Coin from './Coin';
import { choice } from './helpers';
class CoinContainer extends Component {
static defaultProps = {
coins: [
{ side: 'heads', imgSrc: "https://upload.wikimedia.org/wikipedia/commons/3/3f/Pound_coin_front.png" },
{ side: 'tails', imgSrc: "https://upload.wikimedia.org/wikipedia/commons/8/84/Pound_coin_back.png" }
]
}
constructor(props) {
super(props);
this.state = {
currCoin: null,
numOfFlips: 0,
numOfHeads: 0,
numOfTails: 0
};
this.handleClick = this.handleClick.bind(this);
}
flipCoin() {
const newCoin = choice(this.props.coins);
this.setState(oldState => {
return {
currCoin: newCoin,
numOfFlips: oldState.numOfFlips + 1,
numOfHeads: oldState.numOfHeads + (
newCoin.side === "heads" ? 1 : 0),
numOfTails: oldState.numOfTails + (
newCoin.side === "tails" ? 1 : 0)
};
});
}
handleClick(e) {
this.flipCoin();
}
render() {
return (
<div className="CoinContainer">
<h2> FLIP THE COIN!!!</h2>
{this.state.currCoin && <Coin info={this.state.currCoin} />}
<button onClick={this.handleClick}>FLIP!</button>
<p>You flipped the coin for {this.state.numOfFlips} times, got {this.state.numOfHeads} heads and {this.state.numOfTails} tails!!</p>
</div>
);
}
}
export default CoinContainer;
// to keep your component as react-ish as possible, make helper file for other functions
function choice(arr) {
let randomIdx = Math.floor(Math.random() * arr.length);
return arr[randomIdx];
}
export { choice };
import React, { Component } from 'react';
import './Coin.css';
class Coin extends Component {
render() {
return (
<div className='Coin'>
<img src={this.props.info.imgSrc} alt={this.props.info.side} />
</div>
);
}
}
export default Coin;
'react' 카테고리의 다른 글
React form control (0) | 2020.06.14 |
---|---|
React events : event method binding and passing method to child (0) | 2020.06.14 |
State exercise : lottery balls (0) | 2020.06.14 |
More State : data structure and designing state (0) | 2020.06.14 |
More State : setting state using state (0) | 2020.06.13 |