简体   繁体   中英

styling SVG paths in React

I am new to React and I'm trying to add an svg image to my component and add dynamic styles to each of its path. However, I am having issues in doing so. I'm using create-react-app

I imported my svg as a React component

import { ReactComponent as SVGimg} from './img/svg-img.svg';

and used it on my render. I was hoping to add styles to all paths by using a for...of loop which I worked on plain HTML/CSS/JS

render() {
  const svgImg = document.querySelectorAll('svg path')
  for (let path of svgImg) {
    path.classList.add('some-class');
  }

  return(
    <div>
      <SVGimg/>
    </div>
  );
}

I also want to mention that the SVG has a lot of paths

You could add a class to the svg say: <svg><path class='pathClass'></svg>

Then in your React component you can get the path by calling: const path = document.getElementsByClassName('pathClass');

And add the class like so: path.classList.add('some-class');

UPDATE

Since you are using a class component you could call the classList.add() method inside the componentDidMont() native React method like so:

class YourComponent extends Component {
  constructor(props) {
    super(props);

    this.svgRef = React.createRef();
  }

  componentDidMount() {
    this.svgRef.current.classList.add('some-class');
  }

  render() {
    return(
      <div>
        <SVGimg ref={this.svgRef} />
      </div>
    );
  }
}

This will be triggered immediately after the render method finishes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM