What is the best way to import SVG using React.JS

Viewed 2326

My team and I are building a react application and we want to import SVGs not as a string so we'll have the ability to use it as a component.

Since we've installed the project using CRA, SVGR is already installed and is in webpack configuration.

We wanted to know if there's any other way to import the SVG file and not to use the import {ReactComponent as Logo} from '../path' but use something like import Logo from '../path'.

Also is there any benefits from using it that way? Actually we're able to import it the way we want but we can't use it outside of an image tag.

Thanks.

2 Answers

Usually I'm using this package react-svg, and I create a component with it:

import styled, { css } from "styled-components"
import { ReactSVG } from "react-svg"

const IconStyled = styled(ReactSVG)`
    display: inline-flex;
    width: ${props => `${props.size}px`};
    height: ${props => `${props.size}px`};
    align-items: center;
    justify-content: center;

    span {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
    }

    svg {
        fill: black;
        width: 100%;
        height: 100%;
    }

    path {
        fill: ${props => props.color};
    }
`

export default function Icon(props) {
    return (
        <IconStyled
            src= {`/icons/${props.name}.svg`}
            color={props.color || "currentColor"}
            size={props.size}
            wrapper="span"
            {...props}
        />
    )
}

Then, put all the .svg files inside the public folder, and just use them like this:

<Icon name="name-of-icon" size={24} />

You can create Your custom Component like

const ArrowIcon = (props)=>{
  return (
   <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...props}>
  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
)
}

Warning: Careful with Props of SVG. because In React, SVG Attributes may vary from SVG in HTML!

You can use it by


import ArrowIcon from "path/to/svgComponent"

const SimpleReact = ()=>{
  return (
    <div>
      Arrow Icon
      <ArrowIcon className="class" />
    </div>
  )
}

I hope It would work fine ;-)

You can also try SVGR which an awesome library to work with React and SVG. You can download it with

yarn add -D @svgr/cli

Transforms a single file by specifying file as the single argument.

npx @svgr/cli -- icons/clock-icon.svg

You can find more in their Official Docs Link here

Related