Sometimes, we want to turn an SVG string into an image in a React component.
In this article, we’ll look at how to turn an SVG string into an image in a React component.
Turn an SVG String into an Image in a React Component
To turn an SVG string into an image in a React component, we can put the SVG string in a base64 URL string.
Then we can use the base64 URL string as the URL of the image.
For instance, we write:
import React from "react";
export default function App() {
const image =
'<svg xmlns="http://www.w3.org/2000/svg" version="1.2" baseProfile="tiny" width="47.4" height="40.65" viewBox="21 18.5 158 135.5"><path d="M25,50 l150,0 0,100 -150,0 z" stroke-width="4" stroke="black" fill="rgb(128,224,255)" fill-opacity="1" ></path><path d="M25,50 L175,150 M25,150 L175,50" stroke-width="4" stroke="black" fill="black" ></path><g transform="translate(0,0)" stroke-width="4" stroke="black" fill="none" ><circle cx="100" cy="30" r="7.5" fill="black" ></circle><circle cx="70" cy="30" r="7.5" fill="black" ></circle><circle cx="130" cy="30" r="7.5" fill="black" ></circle></g></svg>';
return (
<div>
<img src={`data:image/svg+xml;utf8,${image}`} />
</div>
);
}
to assign the image
variable to a SVG string.
Then we set the src
prop to a base64 URL that has the image
string in it.
Now we should see the SVG displayed on the screen.
Conclusion
To turn an SVG string into an image in a React component, we can put the SVG string in a base64 URL string.
Then we can use the base64 URL string as the URL of the image.