How to import SVG image as React component

Use case

Hugo Capocci
Aug 22, 2017 · 1 min read

Your UX/UI designer created specifics SVG images for your application, and you want to use them with another React components such as those from Material-ui.
Or just you don’t want to create image balise each time you want to use an image in a component, and prefer have a dedicated component.

Example : add an icon into the headbar(appbar) of your React application:

import HeaderIcon from ‘../../icons/header.svg’;

export default class HeaderBar extends Component {
render() {
return ( <AppBar iconElementRight={<HeaderIcon />}/> );
}
}

How to

Install svg-react-loader as a dev dependency:

npm install — save-dev svg-react-loader

Then configure your webpack, by adding rule:

{
test: /\.svg$/,
exclude: /node_modules/,
loader: ‘svg-react-loader’,
query: {
classIdPrefix: ‘[name]-[hash:8]__’,
filters: [ ],
propsMap: {
fillRule: ‘fill-rule’,
},
xmlnsTest: /^xmlns.*$/,
},
}

Ensure to remove other rule that will impact svg files.

Stub it for tests

Create a SVGStub.js file with content as below:

import FontIcon from ‘material-ui/FontIcon’;

module.exports = FontIcon;

In your package.json, in the jest configuration, add the following moduleNameMapper:

“moduleNameMapper”: {

“\\.(svg)$”: “<rootDir>/SVGStub.js”
}

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade