Skip to content

Instantly share code, notes, and snippets.

@panr
Last active April 25, 2023 06:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panr/07ccfb6473bec2f8445b9d4f2391a873 to your computer and use it in GitHub Desktop.
Save panr/07ccfb6473bec2f8445b9d4f2391a873 to your computer and use it in GitHub Desktop.
Custom React component for icons
import React from 'react'
// interface Path {
// windingRule: 'nonzero' | 'evenodd' | undefined
// data: string
// }
// interface IconData {
// name: string
// paths: Path[]
// size: {
// width: number
// height: number
// }
// fill: {
// rgb: string
// hsl: string
// hex: string
// }
// translate: {
// x: number
// y: number
// }
// viewBox: string
// }
// interface Props {
// name: IconData
// size?: string
// color?: string
// viewBox?: string
// translate?: {
// x: number
// y: number
// }
// }
const Icon = props => {
const {
name,
// For UI icons it's good to keep 1:1 ratio. You can reset default value if you want ;-)
size = '1em',
color,
viewBox,
translate,
} = props
return (
<span
style={{
color,
}}
>
<svg
version="1.1"
// How you treat size of the Icon is up to you. I stick to default `1em` or `size` props with 1:1 ratio
width={size || name.size.width}
height={size || name.size.height}
viewBox={viewBox || name.viewBox}
xmlns="http://www.w3.org/2000/svg"
>
<g
transform={
translate
? `translate(${translate.x} ${translate.y})`
: name
? `translate(${name.translate.x} ${name.translate.y})`
: undefined
}
>
{name.paths.map((path, index) => (
<path
d={path.data}
key={index}
style={{
fillRule: path.windingRule,
fill: 'currentColor',
}}
/>
))}
</g>
</svg>
</span>
)
}
export default Icon
@panr
Copy link
Author

panr commented Aug 12, 2019

How to use it?

// index.js

import Icon from `./components/Icon`
// JSON data saved as `icons` variable in `icons.js` file
import { icons } from './icons'

...

<Icon name={icons.home} />

...

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