Last active
April 18, 2020 11:26
Star
You must be signed in to star a gist
Counter component switching classes
This file contains 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
/* src/components/Counter/index.js */ | |
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
import classNames from 'classnames/bind'; | |
import './index.css'; | |
class Counter extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
amount: this.props.amount, | |
classMod: this.changeAppearance(this.props.amount) | |
} | |
} | |
increaseAmount() { | |
this.setState(prevState => ( | |
{amount: prevState.amount +1}) | |
) | |
} | |
decreaseAmount() { | |
this.setState(prevState => ( | |
{amount: prevState.amount -1}) | |
) | |
} | |
changeAppearance(amount){ | |
let newModifier = 'neutral'; | |
if(amount < 0){ | |
newModifier = 'negative' | |
} else if(amount > 0) { | |
newModifier = 'positive' | |
} | |
return newModifier; | |
} | |
componentDidUpdate(prevProps, prevState) { | |
if(prevState.amount !== this.state.amount) { | |
const {amount} = this.state; | |
this.props.callBack(amount); | |
this.setState({classMod: this.changeAppearance(amount)}) | |
} | |
} | |
render() { | |
const { | |
callBack, | |
...other | |
} = this.props; | |
const {amount, classMod} = this.state | |
const counterClasses = classNames( | |
'counter', | |
`counter--${classMod}` | |
); | |
return ( | |
<div data-test="counterComponent" className={counterClasses} {...other}> | |
<button className="counterComponent__button" aria-label='decrease' onClick={() => this.decreaseAmount()}> | |
- | |
</button> | |
<input className="counterComponent__input" type='text' readOnly value={amount} aria-label="current amount"/> | |
<button className="counterComponent__button" aria-label='increase' onClick={() => this.increaseAmount()}> | |
+ | |
</button> | |
</div> | |
); | |
} | |
} | |
Counter.propTypes = { | |
amount: PropTypes.number, | |
callBack: PropTypes.func.isRequired | |
}; | |
Counter.defaultProps = { | |
amount: 0 | |
}; | |
export default Counter; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment