7

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()?

1 Answer 1

23

You need to wrap MyComponent around React.forwardRef()

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 because it's a legacy ref, you should use React.createRef() for class components or useRef for functional component.
You can check for more details in the docs.

e.g.

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

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

OR

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

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Can you help me what to do if the child component is a class type. e.g. class MyComponent extends React.PureComponent
@MahdiBashirpour yes, but you need to show how is the component inside. And your know you are using ref the wrong way right? Did you see that you can't pass a string to ref? Maybe that is the problem
Looks like we get the ref on View. How do we select a child, let's say a TextInput, inside View? ref.current.<what_comes_here?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.