Read and optimize SVG file nodes to render them inline in your website.
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/.
gatsby-source-contentful
and gatsby-source-filesystem
.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} />
}