乐闻世界logo
搜索文章和话题

How do I add color to my svg image in react

1个答案

1

In ReactJS, modifying the colors of SVG elements can be achieved through several different methods. Here are the main approaches:

1. Applying CSS Directly Within SVG Code

If you embed SVG XML code directly within a React component, you can control the fill color by setting the fill attribute. For example:

jsx
function MySvgComponent() { return ( <svg width="100" height="100"> <circle cx="50" cy="50" r="40" stroke="black" strokeWidth="3" fill="red" /> </svg> ); }

In this example, the fill color of the circle is set to red. You can change the color by modifying the value of the fill attribute.

2. Using CSS

If the SVG is imported as a file, you can target SVG elements in CSS using class names or IDs to modify their color:

css
.my-svg { fill: blue; }
jsx
import React from 'react'; import { ReactComponent as MySvg } from './my-svg.svg'; function App() { return <MySvg className="my-svg" />; }

In this example, the SVG file is imported as a React component using ReactComponent and controlled via the my-svg class.

3. Dynamically Changing Colors Using CSS Variables

You can define CSS variables within the SVG and dynamically modify their values in the React component.

css
.my-svg { fill: var(--my-svg-color, black); }
jsx
import React from 'react'; import { ReactComponent as MySvg } from './my-svg.svg'; function App() { return <MySvg style={{ '--my-svg-color': 'green' }} />; }

In this example, the CSS variable --my-svg-color controls the fill color of the SVG, and its value is dynamically set using the style attribute in the React component.

By employing these methods, you can flexibly modify the colors of SVG elements in ReactJS. Select the appropriate method based on your specific requirements and project context.

2024年6月29日 12:07 回复

你的答案