I’m trying to dynamically import local SVG files with Suspense and lazy in React Native (v0.72.3). But I’m getting this error:
ERROR [Error: TransformError Utils/DynamicSvg.tsx: Utils/DynamicSvg.tsx:Invalid call at line 13: import(url)]
Error: Utils/DynamicSvg.tsx:Invalid call at line 13: import(url)
at transformJS (/Users/me/projects/myproj/node_modules/metro-transform-worker/src/index.js:225:15)
at transformJSWithBabel (/Users/me/projects/myproj/node_modules/metro-transform-worker/src/index.js:343:16)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.transform (/Users/me/projects/myproj/node_modules/metro-transform-worker/src/index.js:461:12)
Here is my code:
import { Suspense, lazy } from 'react';
import { View } from 'react-native';
export const DynamicSvg = ({name}: any) => {
console.log("name: " + name);
const LazySvg = lazy(() => {
const url = `./../assets/people/${name}`;
return import(url);
});
return (
<Suspense>
<LazySvg />
</Suspense>
);
};
What am I doing wrong here and how can I fix it?
2
Answers
The React Native doesn’t support
SVG
syntax or file directly. So to fix this you must follow the installation guide:react-native-svg
react-native-svg-transformer
.Then inside your project components, you can write like the following:
It does work, if you need to make a dynamic one, you should pre-import them and write like the following:
The error you’re encountering is due to the fact that React Native’s
import()
function doesn’t support dynamic import of local assets. However, you can achieve dynamic import of local SVG files by using a workaround.Instead of using
import()
directly, you can create a custom function to handle dynamic imports. Here’s how you can modify your code:dynamicImport.ts
, and add the following code:DynamicSvg
component, import thedynamicImport
function and use it to import the SVG file:This workaround uses the
dynamicImport
function to handle the dynamic import of local SVG files. It checks the platform (iOS or Android) and requests the necessary permissions (for Android) before importing the SVG file. Make sure to replace'./dynamicImport'
with the correct path to thedynamicImport.ts
file in your project.Now, your
DynamicSvg
component should be able to import and render the SVG files dynamically.