How to forward refs?
chrispcode opened this issue ยท 5 comments
Alright, so I have been trying to use and imported SVG with react-pose. React-pose has nothing to do with the problem. A simple example would be:
import ExpandSVG from './assets/expand.svg';
const ExpandIcon = React.forwardRef((props, ref) => (
<ExpandSVG ref={ref} />
));
function Example() {
const refExpandIcon = useRef(null);
function handleClick() {
console.log(refExpandIcon);
}
return (
<div>
<button
type="button"
onClick={handleClick}
>
Log ref of the Icon Below
</button>
<ExpandIcon ref={refExpandIcon} />
</div>
);
}
So when I click the button I would expect that the refExpandIcon would be anything but null.
But instead I get a null;
Also I get the following error:
Removing the forwardRef
does not make a difference.
Any ideas? I feel like it is a super simple fix
The author of this library must forward the ref, not you.
You can try this workaround:
function Example() {
const expandIconWrapRef = useRef();
function handleClick() {
console.log(expandIconWrapRef.current.querySelector('svg'));
}
return (
<div>
<button
type="button"
onClick={handleClick}
>
Log ref of the Icon Below
</button>
<span ref={expandIconWrapRef}>
<ExpandIcon />
</span>
</div>
);
}
I see, but isn't a good idea to integrate this in the library as well?
I think it's a good idea. I wrote it in my message:
The author of this library must forward the ref, not you.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
Can we please put this in ๐? Happy to write a PR if needed