Skip to content

Instantly share code, notes, and snippets.

@mieradi
Last active November 18, 2020 20:01
Show Gist options
  • Select an option

  • Save mieradi/744112b01266b09f821ef274869afaee to your computer and use it in GitHub Desktop.

Select an option

Save mieradi/744112b01266b09f821ef274869afaee to your computer and use it in GitHub Desktop.
Reusable SVG component for React, Typescriptm and Styled Components
import React from 'react';
import styled from 'styled-components';
// create a base meta data component
export const SVGBase = styled.svg.attrs({
version: '1.1',
xmlns: 'http://www.w3.org/2000/svg',
xmlnsXlink: 'http://www.w3.org/1999/xlink',
ariaHidden: 'true',
viewBox: '0 0 24 24',
})``;
// add styling that can be changed
interface SVGStylesProps {
fill?: string;
hoverColor?: string;
}
export const SVGStyles = styled(SVGBase)<SVGStylesProps>`
fill: ${({ fill }) => (fill ? fill : 'var(--black)')};
&:hover {
fill: ${({ hoverColor }) => (hoverColor ? hoverColor : 'inherit')};
}
`;
// create a base component
interface SVGProps {
children: React.ReactNode;
fill?: string;
width?: string;
hoverColor?: string;
}
export const SVG: React.FC<SVGProps> = ({
fill,
width,
hoverColor,
children,
}): JSX.Element => {
return (
<SVGStyles width={width} fill={fill} hoverColor={hoverColor}>
{children}
</SVGStyles>
);
};
// USE IT
// pass everything in between the svg tags or the SVG you want to use
export const StarIcon: React.FC<StarIconProps> = ({}): JSX.Element => {
return (
<SVG fill={'#dfdfdf'} hoverColor={'#bf112b'}>
<path d="M24 9.321l-8.4-1.097L12 .75 8.4 8.224 0 9.321l6.171 5.589-1.594 8.126L12 19.04l7.423 3.995-1.594-8.126z" />
</SVG>
);
};
@mieradi
Copy link
Author

mieradi commented Nov 18, 2020

Feel free to grab this if anyone wants a reusable SVG component for React with Styled Components. I made it for work, and wanted to pass it on.

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