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