How to import SVG as a component in CRA
If you use create-react-app you can import a svg file as ReactComponent
, for example:
import { ReactComponent as MyLogo } from './logo.svg';
The ReactComponent
named export is a special type of export provided by SVGR, which allows you to import an SVG file and use it as a React component.
Once the import statement has been executed, the MyLogo variable will contain a React component that represents the SVG file at the specified path (./logo.svg). You can then use this component just like any other React component, by rendering it in your JSX code.
import { ReactComponent as MyLogo } from './logo.svg';
function App() {
return (
<div>
<MyLogo />
</div>
);
}
Tip from CRA documentation:
The imported SVG React Component accepts a title prop along with other props that a svg element accepts. Use this prop to add an accessible title to your svg component.