Importing SVG files as React Components in TypeScript svg files as React Components in a TypeScript project. import React from "react"; import { ReactComponent as SVGIcon } from "~/icons/icon.
There are a few ways to use an SVG in a React app: Use it as a regular image. Import it as a component via bundler magic (SVGR) Include it directly as JSX.
If you use webpack, you can do this by creating a custom types file.
Create a file named custom.d.ts with the following content:
declare module "*.svg" {
const content: any;
export default content;
}
Add the custom.d.ts
to tsconfig.json
as below
"include": ["src/components", "src/custom.d.ts"]
Source: https://webpack.js.org/guides/typescript/#importing-other-assets
Thanks smarx for pointing out use require()
. So in my case it should be:
const logo = require("./logo.svg") as string;
which works fine in *.tsx files
create-react-app 2+
: docs
Add a custom.d.ts
file (I created it on the root path of my src dir) with the correct type (thanks to RedMatt):
declare module '*.svg' {
const content: React.FunctionComponent<React.SVGAttributes<SVGElement>>;
export default content;
}
Install svg-react-loader or some other, then:
import MySVG from '-!svg-react-loader!src/assets/images/name.svg'
Then just use it as a JSX tag:
function f() {
return (<MySVG />);
}
The solution that I found: In ReactJS project, in file react-app-env.d.ts you just remove the space in the comment such as:
Before
// / <reference types="react-scripts" />
After
/// <reference types="react-scripts" />
I hope to help you
You can declare module for svgs the same way as create-react-app:
react-app.d.ts
declare module '*.svg' {
import * as React from 'react';
export const ReactComponent: React.FunctionComponent<React.SVGProps<
SVGSVGElement
> & { title?: string }>;
const src: string;
export default src;
}
see source
I had the same issue while trying out a REACT + typescript tutorial.
What worked for me was the following import statement.
import * as logo from 'logo.svg'
Here are my dependencies in package.json.
"dependencies": {
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-scripts-ts": "3.1.0"
},
Hope it helps someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With