Let’s talk about SVG

Okay ‘90’s song references aside (if you didn’t get that reference then you think I’m old!)

So I’ve been working on a little side project where users can upload an SVG file to use a graphical template for creating fast and simple web layouts.

So I thought this would be a good time to have a look through some of the specific problems that this project has unearthed.

Today its asynchronously loading SVG’s into React and converting them to React elements.


If we have access to our SVG at build then it’s a far more sensible idea to directly import the SVG into our codebase. If we set up our project using create-react-app then we can use a standard import statement to get our SVG as an element variable.

import logo from './logo.svg';

Alternatively, if we need more fine-grained control over our SVG then SVGR provides a simple command-line interface for converting SVG to React components.

npx @svgr/cli logo.svg

We could also employ some standard HTML/CSS methods of displaying an external SVG.

As background-image

This method can be very useful when you don’t need to have any direct control of the SVG within your application aside from sizing and placement of the image. I’ll use inline styles in my script to keep the examples readable.

const Logo = () => {
		return( 
	  	<div
	        style={{
	          backgroundImage: 'url(https://upload.wikimedia.org/wikipedia/commons/4/47/React.svg)',
	          backgroundRepeat: 'no-repeat',
	          backgroundPosition: 'center',
	          backgroundSize: 'contain',
	          height: '500px',
	          width: '500px'
	        }}
	      >
	      </div>
	  )
	}

simple SVG background-image

As an source

const LogoImg = () => {
	  return (
	    <img
	      src='https://upload.wikimedia.org/wikipedia/commons/4/47/React.svg'
	      style={{
	        height: '500px',
	        width: '500px'
	      }}
	    />
	  )
	}

Now the above options are great if all you need to do is display a nice crisp SVG image. It will still be re-sizable and scale beautifully but that’s it!

So far this doesn’t give us much room to customize the look and functionality of our external SVG.

#reactjs #react #svg #reactjs-development #programming

Let's talk about React asynchronously loading SVG
2.75 GEEK