Skip to content

Instantly share code, notes, and snippets.

@Lelith
Last active April 18, 2020 11:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Lelith/aebdb418f5fb81bff521e87f7058d285 to your computer and use it in GitHub Desktop.
Counter component switching classes
/* 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