Last active
March 20, 2019 13:52
-
-
Save jamesmosier/3055217355374e85165277f42e9c1ad3 to your computer and use it in GitHub Desktop.
Slider using useImperativeHandle hook
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 React, { useRef } from 'react'; | |
import Slider from './Slider'; | |
import useSlider from './useSlider'; | |
const MIN_VALUE = 0; | |
const MAX_VALUE = 500; | |
function PriceSlider() { | |
const sliderRef = useRef(null); | |
const [min, max, handleUpdate] = useSlider(MIN_VALUE, MAX_VALUE); | |
function handleSet() { | |
} | |
function handleClear() { | |
sliderRef.current.clear(MIN_VALUE, MAX_VALUE); | |
} | |
return ( | |
<div> | |
<Slider | |
min={min} | |
max={max} | |
step={10} | |
minRange={MIN_VALUE} | |
maxRange={MAX_VALUE} | |
onUpdate={handleUpdate} | |
onSet={handleSet} | |
ref={sliderRef} | |
/> | |
<button type="button" onClick={handleClear}>Clear</button> | |
</div> | |
); | |
} | |
export default PriceSlider; |
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 React, { | |
useEffect, useRef, useImperativeHandle, forwardRef, | |
} from 'react'; | |
import noUiSlider from 'nouislider'; | |
function Slider(props, forwardedRef) { | |
const { | |
min, max, minRange, maxRange, step, | |
} = props; | |
const sliderElement = useRef(); | |
useEffect(() => { | |
const sliderInstance = noUiSlider.create(sliderElement.current, { | |
connect: true, | |
start: [min, max], | |
step, | |
range: { | |
min: [minRange], | |
max: [maxRange], | |
}, | |
}); | |
if (props.onUpdate) { | |
sliderInstance.on('update', props.onUpdate); | |
} | |
if (props.onChange) { | |
sliderInstance.on('change', props.onChange); | |
} | |
return () => sliderInstance.destroy(); | |
}, [props.onUpdate, props.onChange]); | |
useEffect(() => { | |
if (props.onSet) { | |
sliderElement.current.noUiSlider.on('set', props.onSet); | |
} | |
return () => { | |
if (sliderElement.current.noUiSlider) { | |
sliderElement.current.noUiSlider.off('set'); | |
} | |
}; | |
}, [props.onSet]); | |
useImperativeHandle(forwardedRef, () => ({ | |
clear: (defaultMin, defaultMax) => { | |
if (sliderElement.current) { | |
sliderElement.current.noUiSlider.set([defaultMin, defaultMax]); | |
} | |
}, | |
})); | |
return <div ref={sliderElement} />; | |
} | |
export default forwardRef(Slider); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment