Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add refs to functional components using withHandlers in Recompose and call ScrollTo on a ScrollView?

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?

like image 650
GollyJer Avatar asked Aug 14 '17 16:08

GollyJer


People also ask

How do you add a ref to a functional component?

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.

Can we create ref in functional component?

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.

How do I reference a component in React?

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.


2 Answers

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)
like image 89
deepsweet Avatar answered Sep 20 '22 11:09

deepsweet


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} />
like image 25
simPod Avatar answered Sep 21 '22 11:09

simPod