Skip to content

Instantly share code, notes, and snippets.

@dazld
Created May 25, 2015 12:09
Show Gist options
  • Save dazld/e1ba1780da638fb4c950 to your computer and use it in GitHub Desktop.
Save dazld/e1ba1780da638fb4c950 to your computer and use it in GitHub Desktop.
react slider component
'use strict';
import React from 'react';
function clamp (value, minimum, maximum) {
if (maximum === null) {
maximum = Infinity;
}
if (maximum < minimum) {
let swap = maximum;
maximum = minimum;
minimum = swap;
}
return Math.max(minimum, Math.min(value, maximum));
}
export default React.createClass({
getInitialState: function() {
return {
settable: false,
value: 0,
rect: {}
};
},
componentDidMount: function() {
this.setState({
value: this.props.value,
rect: this.getDOMNode().getBoundingClientRect()
});
},
componentWillReceiveProps: function(nextProps) {
this.setState({
value: nextProps.value
});
},
setSettable: function(state) {
this.setState({
settable: state
});
},
handleStart: function(e) {
e.stopPropagation();
e.preventDefault();
this.setSettable(true);
},
handleEnd: function() {
this.setSettable(false);
},
handleClick:function(e){
this.setHeight(e);
},
handleMove: function(e){
if (!this.state.settable) {
return;
} else {
this.setHeight(e);
}
},
setHeight: function(e) {
let pY = e.pageY;
if (e.touches && e.touches.length) {
pY = e.touches[0].pageY;
}
let rect = this.state.rect;
let value = ((pY - rect.top) / rect.height) * this.props.max;
value = clamp(value, 0, this.props.max);
this.props.onUpdate(Math.floor(this.props.max - value));
},
render: function() {
const value = this.state.value;
const barStyles = {
height: ((value / this.props.max ) * 100) + '%'
};
return (
<div className='slider'
onMouseMove={this.handleMove}
onTouchMove={this.handleMove}
onClick={this.handleClick}
onMouseDown={this.handleStart}
onMouseUp={this.handleEnd}
onMouseLeave={this.handleEnd}
onTouchStart={this.handleStart}
onTouchEnd={this.handleEnd}>
<div className="bar" style={barStyles}>
{value}
</div>
</div>
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment