Import and use a SVG file in React.js?

Answered
coderguy asked this question 1 year, 5 months ago
coderguy on Dec 30, 2021

I have a SVG file that I want to import and use in my React.js application:

<svg viewBox="0 0 16 16">
  <path 
    fillRule="evenodd" 
    d="M4.72 3.22a.75.75 0 011.06 1.06L2.06 8l3.72 3.72a.75.75 0 11-1.06 1.06L.47 8.53a.75.75 0 010-1.06l4.25-4.25zm6.56 0a.75.75 0 10-1.06 1.06L13.94 8l-3.72 3.72a.75.75 0 101.06 1.06l4.25-4.25a.75.75 0 000-1.06l-4.25-4.25z"
  >
  </path>
</svg>

How can I import the SVG like this:

import svgIcon from "./file.svg"

And use it in my React.js page.

Thanks in advance!

2 suggested answers
itsbambi on Jan 4, 2022

You can convert your SVG file into a React component like this:

import { Component } from "react"

export default class extends Component {
  render() {
    return (
      <svg viewBox="0 0 16 16">
        <path
          fillRule="evenodd"
          d="M4.72 3.22a.75.75 0 011.06 1.06L2.06 8l3.72 3.72a.75.75 0 11-1.06 1.06L.47 8.53a.75.75 0 010-1.06l4.25-4.25zm6.56 0a.75.75 0 10-1.06 1.06L13.94 8l-3.72 3.72a.75.75 0 101.06 1.06l4.25-4.25a.75.75 0 000-1.06l-4.25-4.25z"
        >
        </path>
      </svg>
    )
  }
}

You can then import and use that component into your React page:

import { Component } from "react"

import SVGFile from "./mySVGFile.js"

export default class extends Component {
  render() {
    return (
      <SVGFile />
    )
  }
}
0 replies
looper003 on Jan 4, 2022 · Edited

You can import a SVG file and render it as a <img /> element:

<img src={svgIcon} />
0 replies
Answered