'Render SVG images in React Native imported from a Preact library
I want to use SVG icons in my React Native app. The icons are imported from a library, which is written in Preact.
When I import the svg from the lib and render it this way:
<View>
<PencilIcon />
</View>
I get this error on mobile:
Error: Expected ref to be a function, a string, an object returned by React.createRef(), or null.
When I put that svg in the React Native repo and import it as a local file, it's rendered correctly. Printing the svg contents in console gave these results:
Imported Pencil icon from the mobile repo itself (import Pencil from '../icons/pencil.svg'
):
<svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
...
</svg>
Imported Pencil icon from library (import { Pencil } from 'my-lib'
}:
var SvgPencil = function SvgPencil(props) {
return /*#__PURE__*/a("svg", pencil_extends({
viewBox: "0 0 20 20",
fill: "none",
xmlns: "http://www.w3.org/2000/svg"
}, props), pencil_path || (pencil_path = /*#__PURE__*/a("path", {
d: "some-svg-data-here"
})));
};
How can I render this svg in react native? I suppose the issue could be related to how the svg is exported from the library. If I could export it "as-is", I guess the issue would be solved. Although I'm not sure why it's not being rendered now, as it's still a react component.
Some configuration info
In native application I installed react-native-svg
and react-native-svg-transformer
and configured metro.config.js
this way:
module.exports = (async () => {
const {
resolver: {sourceExts, assetExts},
} = await getDefaultConfig();
return {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
babelTransformerPath: require.resolve('react-native-svg-transformer')
},
resolver: {
assetExts: assetExts.filter(ext => ext !== "svg"),
sourceExts: [...sourceExts, "svg"]
},
};
})();
In Preact, I use @svgr/webpack
loader for svg files.
Version of preact
in the lib is 10.5.12
, react-native
version in the mobile app is 0.66.4
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|