Reputation: 23
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
Upvotes: 2
Views: 1667
Reputation: 5157
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.
Upvotes: 2