DEV Community

Cover image for Transforming SVG files into React Components 🖼️ ->🧩
Abdulrahman Alblooshi
Abdulrahman Alblooshi

Posted on

Transforming SVG files into React Components 🖼️ ->🧩

Importing SVG files in React

If you've ever faced an issue where you had no idea how to import an SVG file in React.js or any other Javascript Framework then you've probably been in the same situation that I've been in 😢

So what's the solution? SVGR!

SVGR is a tool that applies complex transformations to convert an SVG file to JSX/React Component

So basically it converts an SVG file to a React Component automatically! ✨

Let's assume we had our SVG file as the following:

<svg
  width="200px"
  height="200px"
  viewBox="0 0 200 200"
  version="1.1"
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink"
>
........
........
........
</svg>
Enter fullscreen mode Exit fullscreen mode

It would simply be converted into this form!

import * as React from 'react'

const SvgComponent = (props) => (
  <svg width="1em" height="1em" viewBox="0 0 200 200" {...props}>
    <path d="" fill="#FFF" />
  </svg>
)

export default SvgComponent
Enter fullscreen mode Exit fullscreen mode

I've tried it on Next.js, I've had to do a two step process

First I had to configure my next.config.js file by adding the following:

module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/i,
      issuer: /\.[jt]sx?$/,
      use: ['@svgr/webpack'],
    })

    return config
  },
}
Enter fullscreen mode Exit fullscreen mode

And after that I simply imported my logo as an SVG but wrote it as a React Component into Home by writing the following code:

import Logo from './logo.svg'

const Home = () => (
  <div>
    <Logo />
  </div>
)
Enter fullscreen mode Exit fullscreen mode

It's as simple as that!

SVGR Playground

SVGR's website includes an in-browser SVG -> React Component converter which I've personally used on multiple occasions when I didn't need to install SVGR as a package
https://react-svgr.com/playground/

An image of SVGR Playground

The best way of learning is by experimenting! Click here to visit SVGR's website

Top comments (0)