I have "My React component" as the following:
'use client';
import styles from './range-slider.module.css'
// range input = track & thumb
export default function RangeSlider({minState, maxState} :
{minState: [string, Function], maxState: [string, Function]}) {
const [min, setMin] = minState;
const [max, setMax] = maxState;
const handleMin = (e: React.ChangeEvent<HTMLInputElement>) => {
setMin(parseInt(e.target.value) < parseInt(max)? e.target.value : max);
};
const handleMax = (e: React.ChangeEvent<HTMLInputElement>) => {
setMax(parseInt(e.target.value) > parseInt(min)? e.target.value : min);
};
return (
<div>
<div className={styles.rangeInput}>
<div className={styles.sliderCtrl}>
<input
type="range"
className={`${styles.slider} ${styles.min}`}
min="0"
max="100"
value = {min}
onChange={handleMin}/>
<input
type="range"
className={`${styles.slider} ${styles.max}`}
min="0"
max="100"
value={max}
onChange={handleMax}/>
</div>
<div className={styles.inputCtrl}>
<div className="min">
<input
className="val-input"
type="number"
min="0"
max="100"
value={min}
onChange={handleMin}/>
</div>
<div className="max">
<input
className="val-input"
type="number"
min="0"
max="100"
value={max}
onChange={handleMax}/>
</div>
</div>
</div>
</div>
)
}
However, I suspect it may not be a good practice to pass the useState as a props to the RangeSlider. My question 1 is whether this is good practice and what are the suggest way to do it.
In fact, my primary purpose of mine is just to grab the value of the RangeSlider (i.e. the value of the two range input nested within it) from its parent component, I am grateful if anyone could tell me sth about it, and that’s question 2.
2
Answers
use useRef hook to reference the input element and get what you want.
See my comments, but I’ll write this as an answer.
You already have the value in the parent component
Your parent component (by looking at the API of your
RangeSlider
) must look something along the lines of this:This means that if you want to "grab" the values in the parent component, due to an event handler for example, you already have them in
minState
andmaxState
. Grab them like this: