How to use React.forwardRef() in React Native

Mahdi Bashirpour picture Mahdi Bashirpour · Jan 28, 2020 · Viewed 9.9k times · Source

I am using refs for access child component

<MyComponent
   ref='_my_refs'
   ...
/>

and call them

this.refs._my_refs.scrollToTop();

I get the error below

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Answer

Vencovsky picture Vencovsky · Jan 28, 2020

You need to wrap MyComponent around React.createRef()

e.g.

const MyComponent = React.forwardRef((props, ref) => {
    return (
        <View ref={ref}> // using the ref
            // your component 
        </View>
})

Also, ref='_my_refs' doesn't work, it should be React.createRef() or if it's a functional component useRef.

e.g.

class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this._my_refs = React.createRef();
    }

    render(){
        return (
            // ...
            <MyComponent
                ref={ref => this._my_refs = ref}
                ...
            />
        )
    }
}

OR

const ParentComponent = props => {
    const myRef = React.useRef()    
    return (
        // ...
        <MyComponent
            ref={ref}
            ...
        />
    )
}

If you pass a ref to a functional component and it isn't wrapped around React.forwardRef, it will give you the error

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

And this means MyComponent is a functional component and isn't wrapped around React.forwardRef.