My specific goal is to use the ScrollTo method of a ScrollView but maintain functional component structure.
More generally this requires getting ref to the current component which isn't possible with naked react native.
In Dec 2016 recompose added Allows handlers property of withHandlers to be a factory function but I can't quite figure out how to use it correctly.
How do you add refs to functional components using withHandlers in Recompose and call ScrollTo on a ScrollView?
To create a ref in a functional component we use the useRef() hook which returns a mutable object with a . current property set to the initialValue we passed to the hook. This returned object will persist for the full lifetime of the component. Thus, throughout all of its re-rendering and until it unmounts.
When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current . You may not use the ref attribute on function components because they don't have instances.
In order to get a reference to a React component, you can either use this to get the current React component, or you can use a ref to get a reference to a component you own. They work like this: var MyComponent = React. createClass({ handleClick: function() { // Explicitly focus the text input using the raw DOM API.
You can try something like this:
/* ... */
const MyView = ({ onRef, children }) => (
<View>
<ScrollView ref={onRef} /* ... */>
{children}
</ScrollView>
</View>
)
export default compose(
withHandlers(() => {
let myScroll = null;
return {
onRef: () => (ref) => (myScroll = ref),
scrollTo: () => (value) => myScroll.scrollTo(value)
}
},
lifecycle({
componentDidMount() {
this.props.scrollTo({ x: 0, y: 100, animated: true })
}
})
)(MyView)
Personally I prefer to initiate Ref as a prop
withProps(() => ({
ref: React.createRef(),
})),
And then just pass it to your stateless component
const MyComponent = ({ ref }) => <Foo ref={ref} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With