SVG as React-node in CRA

Hi there, Tom here. As I was sitting and thinking about what nice little learning tip I could tell you next about, I started to revel about that one time my crew and I fell into a trap of the "Icnoyotl"-tribe of the Amazon River's Upper Delta back in the 1920s. There we were, only having one day of food and zero hope left. Our only chance of survial was to convince the tribe's elder that I'm a god called "MEGABYTE", controlling the earth and the sky with my sheer power of will.

But sure you're here to read about how to best import an SVG-file in your CRA-project, so let's talk about it! This little trick can save you a great amount of time, as CRA's webpack config allows us to import SVGs like in the following example:

import { ReactComponent as BrandIcon } from "./assets/brand-icon.svg";

export default function(){
  return <BrandIcon />
}

You get a named export ReactComponent, which can either be used directly or renamed, as I have done here. If desired, you can directly set width and/or height via their props:

import { ReactComponent as BrandIcon } from "./assets/brand-icon.svg";

export default function(){
  return <BrandIcon height={100} width={100} />
}

This will keep the SVG-view contained to the defined boundaries. And because it's just a React-component, you can also provide all standard React-props, such as className, onClick, etc.

And that's about it! Thanks for the quick read!

- Tom


expressFlow is now Lean-Forge