Yacine C
Posted on April 10, 2023
Working with SVG in a React app can give you headaches!
Understanding how to effectively handle and use SVG files in our applications isn't always straightforward. In fact, there are only two distinct scenarios that one may come across.
SVG as a static image
One practical way to handle SVG files is by storing them in an assets folder and importing them like packages:
import MySVG from 'assets/homer-simpson.png';
const Component = () => {
return (
<img src={MySvg} alt='Homer Simpson' />
)
}
SVG with dynamic properties
While the initial method of displaying your SVG is acceptable, there may be instances where you need to modify your SVG properties based on conditional variables and events.
In such cases, a more efficient approach is to create a separate component that solely handles the SVG and its property logic, making it easier to manage and update.
const MySVG = ({color}) => {
return (
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill={color} />
</svg>
);
}
const Component = () => {
const [focused, setFocused] = useState(false);
return (
<button onClick={() => setActive((prev) => !prev)}>
<MySVG color={focused ? "red" : "black"}/>
</button>
)
}
Posted on April 10, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.