Home > OS >  What is ReactComponent and where does it come from when importing an svg in React?
What is ReactComponent and where does it come from when importing an svg in React?

Time:05-11

I'm following a tutorial and in it a .svg file is being imported as a component. The line of code is:

import {ReactComponent as OfferIcon} from '../assets/svg/localOfferIcon.svg';.

I understand that the .svg file is being imported as a component, however, I dont understand where ReactComponent comes from? I've checked the .svg file and it isn't mentioned in it. Is this a special keyword when importing an .svg file? If someone can point me to the documentation then that would also be nice.

CodePudding user response:

I assume you are using Create React App. Create React App uses SVGR to transform .svg files so you can just import them in your React app. The svg file is transformed in a way that it exports a React component called "ReactComponent". That's why you have to import "ReactComponent" from the file and then rename it to whatever you would like!

Find more information in this really nice blog post. Basically, you can just use <svg> tags in your JSX. However, if you want to import .svg files, you will need a transformer that transforms the content of the file into a React component, which just returns the <svg> content in JSX.

  • Related