Skip to content

Instantly share code, notes, and snippets.

@sbadulin
Created July 17, 2019 15:00
Show Gist options
  • Save sbadulin/7871e19235cc30f38313d07463dab0f2 to your computer and use it in GitHub Desktop.
Save sbadulin/7871e19235cc30f38313d07463dab0f2 to your computer and use it in GitHub Desktop.
SVGR custom template
function iconTemplate({ template }, opts, { imports, componentName, props, jsx }) {
const typeScriptTpl = template.smart({ plugins: ['typescript'] });
return typeScriptTpl.ast`
${imports}
import styled, { css } from 'styled-components';
const SvgIcon = (${props}: React.SVGProps<SVGSVGElement>) => (props => ${jsx})({className: props.className});
const ${componentName} = styled(SvgIcon)([],
({ theme, fill, width }) => css\`
width: \${width || theme.sizes.width};
height: \${width || theme.sizes.width};
fill: \${fill || theme.colors.fillColor};
\`
);
export default ${componentName};
`;
}
module.exports = iconTemplate;
@distillery-david-rearte

Hi! I'm getting the following error in my storybook, did you solve this error with something in svgr.config.js?

image

@distillery-david-rearte

yeah it was a problem with configs in that file, it's working fine with this config

module.exports =  {
  expandProps: 'end',
  template
}

@sbadulin
Copy link
Author

Great! Also check this article https://varun.ca/react-icon-system/

@distillery-david-rearte

nice post, but I think it's easier to use webpack plugin in order to apply this custom template with normal imports like

import FacebookIcon from 'components/shared/icons/FacebookIcon.svg';

and that is transparent for every one in the project. Generate a folder with react components is unnecessary unless you require super weird behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment