Read and optimize (Contentful) SVG file nodes to render them inline in your website.
If you want to render static SVG files, use https://www.gatsbyjs.org/packages/gatsby-plugin-react-svg/.
- Read content of your SVG files from
gatsby-source-contentful
andgatsby-source-filesystem
. - Provides original SVG content for further processing
- Optimizes output via SVGO
- Provides a compact data URI via mini-svg-data-uri
- Downloads svg and caches it via createRemoteFileNode
npm i gatsby-transformer-inline-svg
Pass your server connection credentials, the remote cache directory and the directories you want to cache to the plugin options in your gatsby-config.js
:
gatsby-config.js:
module.exports = {
plugins: [
`gatsby-transformer-inline-svg`
]
}
GraphQL Query:
... on ContentfulAsset {
svg {
content # SVG content optimized with SVGO
originalContent # Original SVG content
dataURI # Optimized SVG as compact dataURI
absolutePath #
relativePath #
}
file {
contentType
url
fileName
}
}
... on File {
svg {
content # SVG content optimized with SVGO
originalContent # Original SVG content
dataURI # Optimized SVG as compact dataURI
absolutePath #
relativePath #
}
absolutePath
name
internal {
mediaType
}
}
Rendering:
import React from 'react'
import propTypes from 'prop-types'
import GatsbyImage from 'gatsby-plugin-image'
// Render inline SVG with fallback non-svg images
export default function Image({ svg, gatsbyImageData, file, alt }) {
if (file.contentType === 'image/svg+xml') {
if (svg && svg.content) {
// Inlined SVGs
return <div dangerouslySetInnerHTML={{ __html: svg.content }} />
}
// SVGs that can/should not be inlined
return <img src={file.url} alt={alt} />
}
// Non SVG images
return <GatsbyImage image={gatsbyImageData} alt={alt} />
}