Notes

Implementing SVG icons in React

Edit on GitHub

ReactJS
2 minutes

v1

 1import React from 'react'
 2import './Icon.scss'
 3
 4function Icon({ name, size }) {
 5  return (
 6    <i className="Icon">
 7      <img
 8        src={`/icons/${name}.svg`}
 9        className={`Icon-${name}`}
10        alt={name}
11        width={size ? `${size}px` : '32px'}
12      />
13    </i>
14  )
15}
16
17export default Icon
1import Icon from './Icon'
2
3<Icon name="home" />

Pros

  • Simple, gets the job done

Cons

  • You can not style these like an SVG (e.g. fill, stroke etc.) because they are imported as a static image.
  • Every image you include is a seperate image file requested and loaded

v2

 1import React from 'react'
 2import './Icon.scss'
 3
 4// Import all the svg icons as React Components
 5import { ReactComponent as Bell } from '../../icons/bell.svg'
 6import { ReactComponent as Chatroom } from '../../icons/chatroom.svg'
 7import { ReactComponent as Couple } from '../../icons/couple.svg'
 8
 9// map the passed icon names and the component (i.e. the SVG file) to load
10const icons = {
11  bell: Bell,
12  chatroom: Chatroom,
13  couple: Couple,
14}
15
16function Icon({ name }) {
17  let SVGicon = icons[name]
18
19  return <SVGicon className={`Icon Icon-${name}`} />
20}
21
22export default Icon
1<Icon name="bell" />

Pros

  • You can use SVGs as inline SVGs, no more browser requests for images, just inline code
  • You can style the SVGs with CSS

Cons

  • No ability to edit SVG in JSX

NOTES:

  • if you have a responsive SVG, one that uses <symbol> and <use> and <style> to show different version of the SVG, it’ll only work as a ReactComponent and not as <img src={filename} />