Embedding SVG code into React

Published on
Authors

Why would you want to use SVGs (Scalable Vector Graphics)? The major reasons would be Resolution, Flexibility, and Great Browser Support.

Resolution: SVGs are commonly made with vector-based graphic design software, such as Illustrator, Sketch, and Inkscape. This means they can be enlarged or shrunk to whatever size without them losing resolution or increasing in file size. This is great news :)

Flexibility: Let your creativity run wild with SVGs, they are fully customizable using CSS. Accessibility options can be implemented, and you can add interactivity with JavaScript. You can also provide fallback images or background color if for some weird reason (ancient browsers etc.) SVGs aren’t supported on a particular machine.

Click here to see an amazing SVG based experiment.

Well… great browser support just means exactly that.

caniuse.com availability stats for SVG

There are many ways to embed SVGs into your website regardless of the framework you use. Sara Soueidan in her article details 7 ways of doing this. For this post, however, I’ll be using the inline method with a basic create-react-app. The final file would look like this:

caniuse.com availability stats for SVG

Find the CodeSandbox demo here

View the complete code on Github: completeFile

So let's start

Create your SVG file using your favorite vector tool, save the file, and open with any text editor. You can use the generated code directly, but I recommend optimization using online tools.

The benefits of optimization include: making your SVG code more readable and smaller by taking away all unnecessary header texts your software usually adds.

Next, create a new file and paste the optimized SVG code.

import React from 'react'
export default function SVGFile() {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      xlink="http://www.w3.org/1999/xlink"
      version="1.1"
      id="Layer_1"
      x="0px"
      y="0px"
      viewBox="0 0 38 38"
      enableBackground="new 0 0 38 38"
    >
      <path className="st0" d="M19 19L6.6 15c0.8-2.6 2.5-4.9 4.7-6.5L19 19z" />
      <path className="st0" d="M19 6v13L11.4 8.5C13.5 6.9 16.1 6 19 6z" />
      <path className="st0" d="M19 19v13c-2.9 0-5.5-0.9-7.6-2.5L19 19z" />
      <path className="st0" d="M26.6 8.5L19 19V6C21.9 6 24.5 6.9 26.6 8.5z" />
    </svg>
  )
}

Notice in the code above, the React className rule still applies, so you have to change ‘class’ in your original SVG code to ‘className’. I have exported the styles to an external CSS file, but if I wanted to leave it inline, I would have to add curly braces, the ‘React way’ [see lines 14–16 below]:

import React from 'react'
export default function SVGFile() {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      xlink="http://www.w3.org/1999/xlink"
      version="1.1"
      id="Layer_1"
      x="0px"
      y="0px"
      viewBox="0 0 38 38"
      enableBackground="new 0 0 38 38"
    >
      <style type="text/css">{`.st0{fill:#cdcdcd;} .st1{fill:#cdcdcd;}`}</style>
      <path className="st0" d="M31.4 15L19 19l7.6-10.5C28.8 10.1 30.5 12.3 31.4 15z" />
      <path className="st1" d="M32 19c0 1.4-0.2 2.8-0.6 4L19 19l12.4-4C31.8 16.2 32 17.6 32 19z" />
    </svg>
  )
}

Awesome! all we have to do now is to import this file into our App. As any React component, you can pass props to it for conditional rendering to give desired animation-like effects.

// This is a test comment
import React, { useState, useEffect } from 'react'
import './App.css'
import SVGFile from './svgFile'
function App() {
  const [inputValue1, setInputValue1] = useState('')
  const [calculatedRate, setCalculatedRate] = useState(0)
  const handleChange = (e) => {
    e.preventDefault()
    setInputValue1(e.target.value)
  }
  useEffect(() => {
    const a = inputValue1 >= 100 ? 100 : inputValue1
    let rate = Math.floor((a / 100) * 10)
    rate = isNaN(rate) ? 0 : rate
    setCalculatedRate(rate)
  }, [inputValue1])
  return (
    <div className="App">
      <h1>How would you rate your SVG knowledge?</h1>
      <h2>{`${calculatedRate * 10}%`}</h2>
      <input type="number" id="Score" value={inputValue1} onChange={handleChange} />
      <label htmlFor="Score">Input some value 0 - 100%</label>
      <div className="svgImage">
        <SVGFile active={calculatedRate} />
      </div>
    </div>
  )
}

Summary

Embedding SVGs inline in React opens a whole new world of creative possibilities and when combined with JavaScript animation libraries such as GSAP you can make your projects more impressive.

View the complete code on Github