'React "useRef": no access to method in .current
So in my React Native application, I want to integrate this slider, following the guidance here.
Problem is, I want to get access to the method setLowValue()
of the .current
property of useRef()
, as specified quite at the end of the guidance website. I printed .current
to the console and saw setLowValue()
specified as a function, so it is definitely there. Why can't I access it?
Here is my code:
imports ...
type Props = {
size: number;
setSize: (size: SizeState) => void;
};
const Slider: React.FC<Props> = ({size, setSize}) => {
const slider = useRef(66); // set slider to inital value
console.log('slider ', slider.current.initialLowValue); // doesn't work: "slider.current.initialLowValue is not a function"
return (
<View style={styles.container}>
<RangeSlider
ref={slider}
max={70}
min={50}
step={1}
initialLowValue={size} // I want to have access to this property
value={size}
onValueChanged={value => setSize({size: value})}
/>
</View>
);
};
function mapStateToProps(state: RootState) {
return {
height: state.sizeResult.size,
};
}
const mapDispatchToProps = {
setSize,
};
export default connect(mapStateToProps, mapDispatchToProps)(Slider);
Help will be much appreciated!
Solution 1:[1]
I would suggest setting the initial ref to null
:
const Slider: React.FC<Props> = ({size, setSize}) => {
const slider = useRef(null);
console.log('slider ', slider.current); // null
useEffect(() => {
if (slider.current) {
console.log('slider ', slider.current.initialLowValue); // size
}
}, []);
return (
<View style={styles.container}>
<RangeSlider
ref={slider}
max={70}
min={50}
step={1}
initialLowValue={size} // I want to have access to this property
value={size}
onValueChanged={value => setSize({size: value})}
/>
</View>
);
};
Solution 2:[2]
The ref values are first set on the 'componentDidMount' and 'componentDidUpdate' lifecycle states, which both occur after the first render.
The reason logging might cause confusion is because the logs can/will occur both on the first render (before componentDidMount, with the initial ref.current) and after (with a properly defined ref.current, set via the ref'd component).
The solution here is to access the ref after the component has been mounted, which can be achieved with a useEffect hook.
See: https://reactjs.org/docs/refs-and-the-dom.html
tldr:
useEffect(() => {
console.log(slider.current.initialLowValue);
}, [])
Solution 3:[3]
Try this
<RangeSlider
ref={(input) => { this.slider = input; }}
.......
/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | strdr4605 |
Solution 2 | |
Solution 3 | Rajan |