Ga naar inhoud

Hoe gebruik je SVG's in React?

Package

Installeer de package @svgr/webpack

Terminal window
yarn add -D @svgr/webpack

Config bestanden

  1. bud.config.ts
  • Voeg dit helemaal onderaan toe in de functie:
export default async (bud: BUD) => {
...
bud.hooks.on(`build.module.rules.oneOf`, (rules = []) => {
rules.unshift({
test: /\.svg$/,
use: [`@svgr/webpack`],
});
return rules;
});
bud.alias(`@icons`, bud.path(`resources/images/icons`));
}
  1. tsconfig.json
  • Voeg @icons/*": ["images/icons/*"] toe in compilerOptions.paths:
{
"compilerOptions": {
"paths": {
...
"@icons/*": ["images/icons/*"]
},
...
},
}

SVG’s gebruiken

  • Importeer een svg
import VariabeleNaam from "@icons/functional/arrow.svg";

@icons refereert in dit geval naar resources/images/icons

  • Gebruik ze in je project:
<VariabeleNaam />
  • Zorg dat de icons alleen een viewBox hebben, de height en width kun je dan zo stylen:
<div class="w-4 h-4">
<VariabeleNaam />
</div>