Frontend, React, Next.js

How to use SVGs as React Components in Next.js

How to use SVGs as React Components in Next.js - Stijn Elskens Cover
Using @svgr/webpack to easy import your svgs as a React component!

SVGR turns SVGs into React components that you can easily import in your app. This way you have cleaner files and still have the ability to apply easy CSS on it!

Get started:

npm install --save-dev @svgr/webpack
# or use yarn
yarn add @svgr/webpack -D

Then update your next.config.js:

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

    return config
  },
}


Now you can do the following:

import Logo from 'assets/logo.svg';

const Header = () => {
  return (
    <header>
      <Logo className="max-w-[195px]" aria-label="Homepage" />
    </header>
  );
};

export default Header;


That's it!