Last active
November 18, 2020 20:01
-
-
Save mieradi/744112b01266b09f821ef274869afaee to your computer and use it in GitHub Desktop.
Reusable SVG component for React, Typescriptm and Styled Components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | |
| ); | |
| }; | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.