Using SVG in Next.js & React

Photo by UX Store on Unsplash

How can we use SVG as ReactComponent inside Nextjs & React?

How to use SVG’s in Next.js?

const Icon = ({fill, width, height}) => {
return (
<svg height={height} width={width} fill={fill} viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/>
</svg>
);
}

const ConcreteIcon = (
<div style={{width:'100%',textAlign:'center'}}>
<Icon fill="#9a9a9a" width={100} height={100} />
</div>
);

2 - Babel-plugin-inline-react-svg — Nextjs

npm install --save-dev babel-plugin-inline-react-svgyarn add -D babel-plugin-inline-react-svg
{  "plugins": [    "inline-react-svg"]}
import React from 'react';import CloseSVG from './close.svg';const MyComponent = () => <CloseSVG />;
import React from 'react';const CloseSVG = () => <svg>{/* ... */}</svg>;const MyComponent = () => <CloseSVG />;
import { ReactComponent as Logo } from './logo.svg';function App() {
return (
<div>
{/* Logo is an actual React component */}
<Logo />
</div>
);
}

4 - Use as Image source

<img src='happy.svg' alt='happy' />

Conclusion

You can buy me a coffee!

Senior Full Stack Software Engineer — Javascript — Berlin

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store