Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(react): enable ref option for SVGR in JSX compiler #376

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

stephenwade
Copy link

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

Copy link

stackblitz bot commented Sep 4, 2024

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

@antfu antfu changed the title Enable ref option for SVGR in JSX compiler feat(react): enable ref option for SVGR in JSX compiler Nov 4, 2024
@antfu
Copy link
Member

antfu commented Nov 4, 2024

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?

@Benjamin-htr
Copy link

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.

Copy link

@ShafSpecs ShafSpecs left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@userquin Looks good! The type change ensures ref can be passed correctly, without breaking normal components

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants