Skip to content

Instantly share code, notes, and snippets.

@ridvanaltun
Last active June 25, 2023 17:14
Show Gist options
  • Save ridvanaltun/7fc18e616038cd74d95ebf8535467f6a to your computer and use it in GitHub Desktop.
Save ridvanaltun/7fc18e616038cd74d95ebf8535467f6a to your computer and use it in GitHub Desktop.
SVGR usage on React-Native

Usage

Add below script to your package.json:

+ "icons:create": "svgr ./assets/icons  -d ./src/components/Icons --config-file svgr-config.json --template svg-template.js",
const comments = `
// Auto-generated file created by svgr-cli source svg-template.js
// Run yarn icons:create to update
// Do not edit
`;
const getAttributeValue = (jsx, name) => {
return jsx.find(e => {
return e.name.name === name;
});
};
const template = (variables, {tpl}) => {
const viewBoxAttr = getAttributeValue(variables.jsx.openingElement.attributes, 'viewBox');
const [, , zoomWidth, zoomHeight] = viewBoxAttr.value.value.split(' ');
const aspectRatio = String(zoomWidth / zoomHeight);
return tpl`
${comments}
${variables.imports};
import {ColorValue} from 'react-native';
${variables.interfaces};
interface IIcon extends SvgProps {
size?: string | number;
secondaryColor?: ColorValue;
};
const ${variables.componentName} = (props: IIcon) => {
const aspectRatio = ${aspectRatio};
return (${variables.jsx});
};
${variables.exports};
`;
};
module.exports = template;
{
"typescript": true,
"native": true,
"replaceAttrValues": {
"white": "{props.color || '#FFFFFF'}",
"#FFF": "{props.color || '#FFFFFF'}",
"#FFFFFF": "{props.color || '#FFFFFF'}",
"#fff": "{props.color || '#FFFFFF'}",
"#ffffff": "{props.color || '#FFFFFF'}",
"black": "{props.color || '#000000'}",
"#000": "{props.color || '#000000'}",
"#000000": "{props.color || '#000000'}",
"currentColor": "{props.color || '#000000'}",
"red": "{props.secondaryColor || '#FF0000'}",
"#f00": "{props.secondaryColor || '#FF0000'}",
"#ff0000": "{props.secondaryColor || '#FF0000'}",
"#F00": "{props.secondaryColor || '#FF0000'}",
"#FF0000": "{props.secondaryColor || '#FF0000'}"
},
"svgProps": {
"width": "{props.size || props.width || (props.height && Math.floor(+props.height * aspectRatio)) || 256}",
"height": "{props.size || props.height || (props.width && Math.floor(+props.width / aspectRatio)) || 256}"
},
"svgoConfig": {
"plugins": [
{
"name": "preset-default",
"params": {
"overrides": {
"removeViewBox": false
}
}
},
{
"name": "removeXMLNS",
"active": true
}
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment