I would like to have a custom hook that would provide me with a ScrollView
component and a function to imperatively control the scrolling of that given component.
I'm using a library called react-native-keyboard-aware-scroll-view, which allows me to catch the reference of the component trough a prop called innerRef
. Through that reference I have access to a series of methods that I can use to manipulate the scrolling.
The only way that I found for that "control function" to have access to the reference while being outside the scope of the ScrollView
component was to create that ref
globally using React.createRef
like below:
const ref = createRef();const ScrollView = ({ children, ...props }) => { return (<KeyboardAwareScrollView {...props} innerRef={(inner) => { ref.current = inner; //adding ref to scrollview }}> {children}</KeyboardAwareScrollView> );};const useScrollTo = () => { const scrollTo = (position: number) => { if (ref.current && position) { /* controlling scroll using ref */ ref.current.scrollTo({ x: 0, y: position, animate: true }); } }; return { ScrollView, scrollTo };};export default useScrollTo;
This feels anti-pattern to me, so I'd like to know if there's a proper way for me to do this without the need of having a ref in the global scope like this. Is this even possible?