How to import SVG image as React component
Use case
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”
}
