If you are a react-native developer and getting this kind of error while displaying .png image or svg image then this blog can be useful to you. The error is shown below while loading the .png image. If you print the path then you will get undefined.
Solution:
The issue often comes due to an issue with the setup of the react-native-svg
library or missing configuration. Here are steps to resolve the issue:
1. Install react-native-svg
Make sure you’ve installed the react-native-svg
library, which is essential for rendering SVGs in React Native.
npm install react-native-svg
or
yarn add react-native-svg
2. Install react-native-svg-transformer
(for local SVG files)
If you’re importing local .svg
files directly into your components, you also need the react-native-svg-transformer
package to transform SVG files during build:
npm install react-native-svg-transformer
or
yarn add react-native-svg-transformer
3. Configure Metro for SVG
In order for the Metro bundler to handle .svg
files, update your metro.config.js
file like this:
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
const {
resolver: { sourceExts, assetExts },
} = getDefaultConfig(__dirname);
const config = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
babelTransformerPath: require.resolve('react-native-svg-transformer'),
},
resolver: {
assetExts: assetExts.filter(ext => ext !== 'svg'),
sourceExts: [...sourceExts, 'svg'],
},
};
module.exports = mergeConfig(defaultConfig, config);
4. Clear cache and rebuild
After making changes, clear your cache and rebuild the project to avoid any old cached configurations:
npx react-native start --reset-cache
Then , run the project:
npx react-native run-android
npx react-native run-ios
Common Issues
- iOS-specific issues: Sometimes,
react-native-svg
doesn’t automatically link correctly for iOS in older versions of React Native. You can try linking it manually:
npx pod-install
- Undefined imports: Make sure that the paths in your imports are correct and that you’re not mixing up named imports and default imports for SVG components.
Following these steps should resolve the issue with an undefined Svg
and PNG imports in your React Native project.