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()?
React forwardRef is a method that allows parent components pass down (i.e., “forward”) refs to their children. Using forwardRef in React gives the child component a reference to a DOM element created by its parent component. This then allows the child to read and modify that element anywhere it is being used.
Ref Forwarding – forwardRef Ref Forwarding is the passing of a ref from a parent component to one of its child components. We can create ref using useRef() in React Hooks. Right now, “myRef” pointed to a null value. But we can attach it to React Components using the “ref” attribute.
forwardRef to obtain the ref passed to it, and then forward it to the DOM button that it renders: const FancyButton = React. forwardRef((props, ref) => ( <button ref={ref} className="FancyButton"> {props. children} </button> )); // You can now get a ref directly to the DOM button: const ref = React.
ForwardRef gives a child component a reference to a DOM entity created by its parent component in React. This helps the child to read and modify the element from any location where it is used. How does forwardRef work in React? In React, parent components typically use props to transfer data down to their children.
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
.
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