react-jam-ui
Version:
React JAM UI components
111 lines (98 loc) • 3.43 kB
JavaScript
import React from 'react';
import classNames from 'classnames';
import Input from '../Input'
import './styles.styl'
export default class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
value: parseFloat(props.value),
step: props.step || 1,
align: props.align || 'center'
}
}
componentWillReceiveProps(nextProps) {
this.setState({
value: nextProps.value
});
}
onMinusCapture = e => {
if (!this.props.disabled) {
let val = this.state.value - this.state.step;
val = val < this.props.min ? this.props.min : val;
this.setState({value: val})
if(this.props.onChange) {
e.target.value = val
this.props.onChange(e)
};
}
}
onPlusCapture = e => {
if (!this.props.disabled) {
let val = this.state.value + this.state.step;
val = val > this.props.max ? this.props.max : val;
this.setState({value: val})
if(this.props.onChange) {
e.target.value = val
this.props.onChange(e)
};
}
}
onChangeCapture = e => {
if (this.props.directChange && !this.props.disabled) {
let val = parseFloat(e.target.value);
if (val) {
val = val < this.props.min ? this.props.min : val;
val = val > this.props.max ? this.props.max : val;
} else {
val=''
}
e.target.value = val;
this.setState({value: val})
if(this.props.onChange) this.props.onChange(e);
}
}
render() {
let classes = classNames('counter', this.props.variant, this.props.size, this.props.className, {
'disabled': this.props.disabled,
'error': this.props.error,
'valid': this.props.valid
});
const id = this.props.id ? `counter_${this.props.id}` : '';
const inputID = this.props.id ? `${id}_input` : '';
const plusID = this.props.id ? `${id}_plus` : '';
const minusID = this.props.id ? `${id}_minus` : '';
return (
<div
className={ classes }
id={ id }
>
<i
className='counter__minus'
onClick={ this.onMinusCapture }
id={minusID}
>-</i>
{
this.props.directChange
? <Input
variant={this.props.variant}
type='text'
size={this.props.size}
disabled={this.props.disabled}
value={this.state.value}
bar={this.props.bar}
align={ this.state.align }
onChange={ this.onChangeCapture }
id={inputID}
/>
: <span className={`counter_num ${this.state.align}`}>{ this.state.value }</span>
}
<i
className='counter__plus'
onClick={ this.onPlusCapture }
id={plusID}
>+</i>
</div>
)
}
}