Search code examples
reactjsreact-nativereact-hooksuse-ref

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

  • 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>
      );
    };