unplugin-icons icon indicating copy to clipboard operation
unplugin-icons copied to clipboard

Enable ref option for SVGR in JSX compiler

Open stephenwade opened this issue 1 year ago • 1 comments

Description

In my project, I want to pass a ref to the generated React component, but it doesn't do anything and I get this error in the browser console:

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

This PR enables SVGR's ref option if we are using React, which forwards ref to the root SVG tag.

Linked Issues

Additional context

stephenwade avatar Sep 04 '24 23:09 stephenwade

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

I don't know enough about React to know the trade-off of changing this behavior - Is there any React dev reviews, or explain it a bit? Should we make it opt-in, or it's a generally better solution for handling icons?

antfu avatar Nov 04 '24 13:11 antfu

Hi !

I'm in favour of this change. I know that the react-icons suffers from the same problem of ref not being passed to the component (like this issue on their repo) but since they don't use svgr, the problem is harder to fix.

It's common in react to want to pass the ref from a parent component to its child component. For example, this component of chakra-ui lib icon passes the ref of the component to the child icon. But if the child component does not properly forward the ref, then you get the warning in the console.

Benjamin-htr avatar Nov 04 '24 15:11 Benjamin-htr

@antfu There are no negative comments and 2 positive ones. We have been patching unplugin-icons with this change in a fairly large project at work and seen no issues with it. Can it be merged soon?

stephenwade avatar Dec 03 '24 00:12 stephenwade