Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display svg icons(.svg files) in UI using React Component?

Tags:

reactjs

svg

I have seen a lot of libraries for svg on react but none gave me how to import an svg file in the react component. I have seen code which talk about bring the svg code into react rather than using the .svg icon as image and show it in the UI.

Please let me know if there are ways to embed the icon.

like image 997
Kamaraju Avatar asked Feb 17 '17 11:02

Kamaraju


People also ask

How do I run a SVG file in React?

SVGs can be imported and used directly as a React component in your React code. The image is not loaded as a separate file, instead, it's rendered along the HTML. A sample use-case would look like this: import React from 'react'; import {ReactComponent as ReactLogo} from './logo.

How do I display SVG icons?

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document. If you did everything correctly, your webpage should look exactly like the demo below.

How do I use SVG in Create-React-app?

Using SVGs as component with create-react-app To do this, first you will have to import your SVG like so: import { ReactComponent as MyLogo } from './logo. svg'; Then you may use your imported SVG as a component.


1 Answers

If you use create-react-app 2.0 you can now do it like this:

import { ReactComponent as YourSvg } from './your-svg.svg'; 

And then use it just like you would normally use a component:

const App = () => (  <div>    <YourSvg />  </div> ); 
like image 158
Tsuni Avatar answered Sep 22 '22 06:09

Tsuni