2r-stepper
Version:
2R library stepper component implemented in React
119 lines (98 loc) • 2.92 kB
JavaScript
'use strict';
import React from 'react';
import classnames from 'classnames';
import StepperStyle from './2r-stepper.style';
class Stepper extends React.Component {
/**
* Constructor
* Sets `state` and `config` based on passed props
*
* @method construtor
*/
constructor(props) {
super(props);
this.state = {
val: this.props.initialValue || 0
};
this.config = {
stepValue: this.props.stepValue || 1,
allowNegativeValues: this.props.allowNegativeValues || false,
classes: this.props.classes || ''
};
}
/**
* Creates the base wrapper classes
*
* @method constructBaseWrapperClasses
* @return {String} Base wrapper classes
*/
constructBaseWrapperClasses() {
let classesArr = this.config.classes ? this.props.classes.split(' ') : [];
return classnames('2r-stepper', classesArr);
}
/**
* Increment the value of the stepper
*
* @method incrementValue
*/
incrementValue() {
this.setState({
val: this.state.val + this.config.stepValue
});
}
/**
* Decrement the value of the stepper
*
* @method decrementValue
*/
decrementValue() {
this.setState({
val: this.state.val - this.config.stepValue
});
}
/**
* Return whether we need to disable the decrement button or not
* User can pass in `allowNegativeValues=true` as props to enable going below
* zero. Otherwise, the button becomes disabled when reaching `0` or when the
* difference between the current value and the step value will go below `0`
*
* @method disableDecrementButton
* @return {Boolean} Whether we need to disable the decrement button
*/
disableDecrementButton() {
let isZeroOrBelow = !this.state.val ||
this.state.val - this.config.stepValue < 0;
return !this.config.allowNegativeValues && isZeroOrBelow;
}
render() {
let baseWrapperClasses = this.constructBaseWrapperClasses();
let isDecrementBtnDisabled = this.disableDecrementButton();
return (
<div className={ baseWrapperClasses }
style={ StepperStyle.wrapper } >
<button className="2r-stepper__button"
style={ StepperStyle.button }
onClick={ this.decrementValue.bind(this) }
disabled={ isDecrementBtnDisabled }>
-
</button>
<div className="2r-stepper__value"
style={ StepperStyle.value }>
{ this.state.val }
</div>
<button className="2r-stepper__button"
style={ StepperStyle.button }
onClick={ this.incrementValue.bind(this) }>
+
</button>
</div>
);
}
}
Stepper.propTypes = {
initialValue: React.PropTypes.number,
stepValue: React.PropTypes.number,
allowNegativeValues: React.PropTypes.bool,
classes: React.PropTypes.string
};
export default Stepper;