codesandbox-client icon indicating copy to clipboard operation
codesandbox-client copied to clipboard

Adding ref to an svgr component

Open OriR opened this issue 3 years ago • 4 comments

🐛 bug report

Preflight Checklist

  • [x] I have read the Contributing Guidelines for this project.
  • [x] I agree to follow the Code of Conduct that this project adheres to.
  • [x] I have searched the issue tracker for an issue that matches the one I want to file, without success.

Description of the problem

when importing an svgr component in a react sandbox, you cannot pass a ref to that component because it doesn't use forwardRef internally to generate it. This differs from the default behavior in react-scripts.

How has this issue affected you? What are you trying to accomplish?

Add a ref to an SVG component in order to add a tooltip to it.

To Reproduce

import { render } from 'react-dom';
import { ReactComponent as SvgComponent } from './path/to/file.svg';

const App = () => (<SvgComponent ref={ref => (window.testingRef=ref)} />);

render(<App />, document.getElementById('root'));

the above produces an error in the console and doesn't invoke the ref function.

I believe this should be the default behavior like it is in CRA, however if decided against it, adding support for a global .svgrrc file would also help as we would be able to add our own custom configuration if needed.

Link to sandbox: link (optional)

Your Environment

Software Name/Version
Сodesandbox
Browser
Operating System

OriR avatar Apr 09 '22 21:04 OriR

Hey @OriR - Have you got a link to a sandbox where this is occurring?

JamesACS avatar Apr 28 '22 13:04 JamesACS

Hey @JamesACS Sorry for the late response

Here's a sandbox where it's happening (it's brand new)

This is the error react is giving me

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

OriR avatar Aug 16 '22 12:08 OriR

So @OriR , it looks like this is related to your app structure, Function components cannot be given refs because they don't have an instance. Removing the ref will fix the warning or you can forwardRef if you want to assign the ref to some of the input field in your component.

There's some Documentation from React that may help you resolve this: https://reactjs.org/docs/forwarding-refs.html

JamesACS avatar Aug 19 '22 15:08 JamesACS

@JamesACS Although you're right that is related to react not allowing refs on function components, it is however allowed with the default configuration of CRA (create react app) for some time now The codesandbox I showed here uses CRA to run, so, I'd imagine it would work the same way as the default CRA configuration, but unfortunately it doesn't.

I think I looked into it a while back and saw some code in codesandbox-client that overrides some svg configuration (that might explain this), but I haven't had the time to look deeper into it.

OriR avatar Aug 19 '22 16:08 OriR