Solving the Unsolvable: SVG Icons With React/Preact & Webpack

import svgSource from ‘./image.svg’
import Icon from 'app/UI/_lib/Icon'<Icon type='danger' size='big' color='small' />
import Icon from 'app/UI/_lib/Icon'
import dangerIcon from 'app/UI/_lib/danger.svg'
<Icon source={dangerIcon} size='big' color='small' />
import DangerIcon from 'app/UI/_lib/danger.svg'<DangerIcon fill='#f00' width='1rem' />
import Icon from 'app/UI/_lib/Icon'
import DangerIcon from 'app/UI/_lib/danger.svg'
<Icon component={DangerIcon} size='big' color='red' />
import DangerIcon from 'app/UI/_lib/danger.svg'<DangerIcon size='big' color='red' />
//=> <svg fill='#f00' width='1rem'>...</svg>
const iconsPath = path.resolve(process.cwd(), 'app/UI/_lib/Icon')
...
{
test: /\.svg$/,
use: [
{
loader: 'hoc',
options: {
useDefault: true,
path: path.join(iconsPath, 'index.jsx') // 👈 Path to HoC
}
},
'desvg/react', // 👈 Convert SVG to components
'svg'
],
include: iconsPath
},
...
import React from 'react'
import classNames from 'classnames'
export default function (Svg) {
return function Icon ({
size = 'medium',
color = 'black',
style = 'solid'
}) {
return (
<div
className={classNames(
'Icon',
`is-${size}`,
`is-${color}`,
`is-${style}`
)}
>
<Svg fill='currentColor' />
</div>
)
}
}

--

--

Software engineer & entrepreneur 🍄🐑💨

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store