Skip to content

Instantly share code, notes, and snippets.

@joeldbirch
Last active May 25, 2019 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeldbirch/52fd5409cec4151b7670fdf22859e07e to your computer and use it in GitHub Desktop.
Save joeldbirch/52fd5409cec4151b7670fdf22859e07e to your computer and use it in GitHub Desktop.
React component providing a replacement img tag which makes fetchSvgInline work with server-side rendering (tested on Gatsby). "fetchSvgInline" (by @stowball) fetches a remote SVG as an <img> and converts it to an inline SVG.
import React, {Component, createRef } from 'react'
// Include Matt Stow's fetchSvgInline from https://gist.github.com/stowball/e51dde035346eba783f3d8b54dbbf2a4
import { fetchSvgInline } from '../utilities/helpers'
export default class extends Component {
constructor(props) {
super(props)
this.imgRef = createRef()
}
componentDidMount() {
const img = this.imgRef.current
if (img && img.complete) {
this.svgLoaded({currentTarget: img})
}
}
svgLoaded(e) {
return (window !== 'undefined' && 'fetch' in window)
? fetchSvgInline(e.currentTarget)
: true
}
render() {
return (
<img
alt={this.props.alt}
lazyload="lazy"
onLoad={this.svgLoaded}
ref={this.imgRef}
{...this.props}
/>
)
}
}
@joeldbirch
Copy link
Author

joeldbirch commented May 25, 2019

Usage:

import SvgImg from './SvgImg'

// Later in your page…

<SvgImg
  alt=""
  className="some classes here"
  src="/images/logo.svg"
/>

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