Skip to main content

Command Palette

Search for a command to run...

The easiest way to add SVG icons in React

Published
•2 min read•View as Markdown
The easiest way to add SVG icons in React

SVG images can be used a couple different ways in react, this is my favorite option.

I create a file for the svg, and make it into a JSX component.

export default function FacebookSvg() {
    return (<div>
        <svg ... />
    </div>
    )
}

Simple Icons is a good site for finding brand icons like Facebook. https://simpleicons.org/?q=facebbok

Just search for the brand and click the image to copy the svg code.

We have to do some edits to make this code behave the way I like, such as replacing or adding the height and width properties, and change the kebab-case properties to camelCase so it works for React.

// add width and height
<svg
width="100%"
height="100%"
...
/>

Setting the width and height to 100% makes you able to scale the svg by setting a size on the wrapping container in HTML.

<div style="width: 30px; height: 30px;">
    <FacebookSVG />
</div>
// replace kebab-case with camelCase
clip-path becomes clipPath
xlink:type becomes xlinkType
etc

The icons from Simple Icons all have white color, but if you want to set another color you can pass that as a prop to the SVG

export default function FacebookSvg(fillColor: string ) {
    return (
        <svg 
            height="100%"
            width="100%"
            role="img"
            viewBox="0 0 24 24" 
            xmlns="http://www.w3.org/2000/svg">
            <title>Facebook</title>
            <path 
                fill={fillColor}
                // or do: fill="currentColor"
                d="M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978.401 0 .955.042 1.468.103a8.68 8.68 0 0 1 1.141.195v3.325a8.623 8.623 0 0 0-.653-.036 26.805 26.805 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.686 1.686 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103-.287 1.564h-3.246v8.245C19.396 23.238 24 18.179 24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.628 3.874 10.35 9.101 11.647Z"/>
            </svg>)
}

More from this blog

The Build Log by Stefan Skorpen

18 posts

I'm a full stack developer that likes to code, so I want to share some tips from what I learn by coding in public!