See this gist for react-input-slider's types. Originally written for care.tv.
Last active
September 29, 2019 12:03
-
-
Save srph/5bf5b0b38c7f13123cdb0dc420e6f208 to your computer and use it in GitHub Desktop.
react-input-slider: Lazily update value only when the drag ends.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react' | |
import { useState, useRef } from 'react' | |
import Slider, { SliderValue } from 'react-input-slider' | |
type Style = { [key: string]: any } | |
interface Props { | |
value: number | |
min: number | |
max: number | |
styles?: { | |
active?: Style | |
thumb?: Style | |
track?: Style | |
} | |
onChange?: (value: number) => void | |
} | |
/** | |
* react-input-slider calls props.onChange each drag move. | |
* This component lazily updates the value only after the drag / click. | |
* @param props | |
*/ | |
function UiInputSlider(props: Props) { | |
const [slackX, setSlackX] = useState<number>(() => props.value) | |
const slackXRef = useRef(slackX) // Access the updated slackX from the other event listeners | |
const [isDragging, setIsDragging] = useState<boolean>(false) | |
function handleQueueChange({ x }: SliderValue) { | |
setIsDragging(true) | |
slackXRef.current = x | |
setSlackX(x) | |
} | |
function handleCommitChange() { | |
props.onChange && props.onChange(slackXRef.current) | |
setIsDragging(false) | |
} | |
return ( | |
<Slider | |
axis="x" | |
x={isDragging ? slackX : props.value} | |
xmin={props.min} | |
xmax={props.max} | |
onChange={handleQueueChange} | |
onClick={handleCommitChange} | |
onDragEnd={handleCommitChange} | |
styles={props.styles} | |
/> | |
) | |
} | |
export default UiInputSlider |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment