Reputation: 661
I've recently noticed that in ReactJS passing ref
to a component as property is not possible.
Here's my Code:
class A extends React.Component{
render(){
return <B
ref={ref=>this.bRef = ref}
/>
}
}
class B extends React.Component{
render(){
console.log(this.props.ref) //=>undefined
return <div
{...this.props}
/>
}
}
this.bRef
will be undefined in A
. Is there a explanation about this?
Upvotes: 1
Views: 1113
Reputation: 1935
Is there a explanation about this?
The issue you are seeing is due to the fact that key
and ref
are special props.
See
Most props on a JSX element are passed on to the component, however, there are two special props (ref and key) which are used by React, and are thus not forwarded to the component.
For instance, attempting to access this.props.key from a component (i.e., the render function or propTypes) is not defined. If you need to access the same value within the child component, you should pass it as a different prop (ex:
<ListItemWrapper key={result.id} id={result.id} />
). While this may seem redundant, it’s important to separate app logic from reconciling hints.
To access ref in child pass it in a different prop.
Say you create a ref
like
const ref = React.createRef();
and then you pass it to your component as shown below:
<FancyButton forwardedRef={ref} text="Click ME!" />
where inside the FancyButton
the ref will be available as
<button
onClick={() => {
this.logRef(forwardedRef);
}}
ref={forwardedRef}
>
{text}
</button>
where logRef
is defined as
logRef(myref) {
console.log(myref.current);
}
a working example can be seen at (Click on the button and check the console) : https://codesandbox.io/s/ko6wnrorv
Upvotes: 2
Reputation: 2419
ref does not behave like a regular props. It has a special meaning.
class A extends React.Component{
render(){
return <B
ref={ref=>this.bRef = ref}
/>
}
}
what it means here is, you are getting a reference of component 'B' in component 'A'. That is, you can use this.bRef to call some methods in component 'B' from component 'A'
Note: this.bRef will get it's value only after A and B is rendered until then it will be undefined.
Upvotes: 0