From b456b59c4448d6b495f23c6dd858895ac87a1953 Mon Sep 17 00:00:00 2001 From: orangemug Date: Fri, 2 Nov 2018 08:28:51 +0000 Subject: [PATCH] Fix to allow high precision on text input and integer on range. --- src/components/inputs/NumberInput.jsx | 39 ++++++++++++++++++--------- src/styles/_input.scss | 10 +++++++ 2 files changed, 37 insertions(+), 12 deletions(-) diff --git a/src/components/inputs/NumberInput.jsx b/src/components/inputs/NumberInput.jsx index 714ca56..3371e44 100644 --- a/src/components/inputs/NumberInput.jsx +++ b/src/components/inputs/NumberInput.jsx @@ -23,18 +23,13 @@ class NumberInput extends React.Component { } } - static getDerivedStateFromProps(props, state) { - return { - value: props.value - }; - } - changeValue(newValue) { const value = parseFloat(newValue) const hasChanged = this.state.value !== value if(this.isValid(value) && hasChanged) { this.props.onChange(value) + this.setState({ value: value }) } else { this.setState({ value: newValue }) } @@ -73,6 +68,27 @@ class NumberInput extends React.Component { } } + onChangeRange = (e) => { + const val = parseFloat(rawValue, 10); + const step = this.props.rangeStep; + let out = val; + + if(step) { + // Can't do this with the range step attribute else we won't be able to set a high precision value via the text input. + const snap = val % step; + + // Round up/down to step + if (snap < step/2) { + out = val - snap; + } + else { + out = val + (step - snap); + }; + } + + this.changeValue(out); + } + render() { let rangeEl; @@ -83,22 +99,21 @@ class NumberInput extends React.Component { ) { rangeEl = ( this.changeValue(e.target.value)} + value={this.state.value} + onChange={this.onChangeRange} onBlur={this.resetValue} /> ); } - return
+ return
{rangeEl}