DEV Community

Cover image for How to import SVG in React
Ahmed Zougari
Ahmed Zougari

Posted on

How to import SVG in React

Method 1

using it as a source for img tag

import icon from './icon.svg';

const Footer = () => {
  return(
    <Footer>
      {/*... */}
      <a href='#'>
        <img src={icon} alt=""/>
      </a>
    </Footer>
  )
}
Enter fullscreen mode Exit fullscreen mode

Method 2

use it as component. In this way you can style SVG with CSS. change colors or animation with attributes like (storke, fill, stroke-dasharray ...)

import { ReactComponent as Icon } from './icon.svg';

const Footer = () => {
  return(
    <Footer>
      {/*... */}
      <a href='#'>
        <Icon />
      </a>
    </Footer>
  )
}
Enter fullscreen mode Exit fullscreen mode

Method 3

Include SVGs directly in JSX. This is like the previous method but it may not be scalable for a large number of SVGs.

const Icon = () => {
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
  <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/>
</svg>
}

const Footer = () => {
  return(
    <Footer>
      {/*... */}
      <a href='#'>
        <Icon />
      </a>
    </Footer>
  )
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)