facebook / create-react-app

Set up a modern web app by running one command.
https://create-react-app.dev
MIT License
102.74k stars 26.86k forks source link

SVGR enable forward ref for root node #5456

Closed GasimGasimzada closed 5 years ago

GasimGasimzada commented 6 years ago

Is this a bug report?

No

Did you try recovering your dependencies?

Yes

Which terms did you search for in User Guide?

Yes. SVG Ref; SVG forwardRef

Environment

Environment:
  OS:  macOS 10.14
  Node:  10.9.0
  Yarn:  1.9.4
  npm:  6.2.0
  Watchman:  4.7.0
  Xcode:  Xcode 10.0 Build version 10A255
  Android Studio:  Not Found

Packages: (wanted => installed)
  react: ^16.5.2 => 16.5.2
  react-dom: ^16.5.2 => 16.5.2
  react-scripts: 2.0.3 => 2.0.3

Steps to Reproduce

  1. Create ref in the component
  2. Pass ref to the SVG component

Expected Behavior

Get the root node of svg file (i.e the svg element)

Actual Behavior

Warning: Stateless function components cannot be given refs. Attempts to access this ref will fail.

Reproducible Demo

    import React, { Component } form 'react';
    import { ReactComponent as WavyBackground } from './assets/wavy-bg.svg';

    class App extends Component {
        someRef = React.createRef();

        componentDidMount() {
            console.log(this.someRef);
        }

        render() {
            return (<WavyBackground ref={this.someRef} />);
        }
    }

Additional Thoughts

At least for me, one of the main reasons for using SVG as inline/component rather than from a file is to be able to perform operations on it via CSS or JS. Most of the time it is about animations. Many animation libraries such as GSAP or AnimeJS require a DOM node or selector to perform the animations. Currently, the only way to pass objects is to pass a selector in the following way:

animejs({
    targets: '.containerClassOfReactComponent path.line'
});

However, if SVGR --ref option is passed (at least in CLI), the generated SVG component's ref will be forwarded to the svg root element; therefore, we will be able to ref to the SVG component if we need to access the element.

GasimGasimzada commented 6 years ago

I was able to figure out how SVGR works and how to add the feature to react script: https://github.com/facebook/create-react-app/pull/5457