When trying to load an SVG image this way:
export const query = graphql`
query {
fileName: file(relativePath: { eq: "logo_large.svg" }) {
childImageSharp {
fluid(maxWidth: 1060) {
...GatsbyImageSharpFluid_withWebp_tracedSVG
}
}
}
}
`
I get TypeError: Cannot read property 'childImageSharp' of null
If I try the exact same but with a .jpg or .png image, it works, so the relative path must be correct. Any thing I should have in special consideration with SVG's?
If you are trying to use SVG like <img src="image. svg"> or as a CSS background-image , and the file is linked to correctly and everything seems right, but the browser isn't displaying it, it might be because your server is serving it with an incorrect content-type.
The gatsby-image package is now deprecated. The new Gatsby image plugin has better performance, cool new features and a simpler API. See the migration guide to learn how to upgrade. Speedy, optimized images without the work. gatsby-image is a React component specially designed to work seamlessly with Gatsby’s GraphQL queries.
The gatsby-image is a React component that allows us to render an optimized image (for both fixed and full-width images) through <Img />. While gatsby-transformer-sharp will expose the node, childImageSharp, for processing your images. Once the plugins are installed, add the gatsby-transformer-sharp plugin to your gatsby-config.js file.
Depending on the gatsby starter you used, you may need to include gatsby-transformer-sharp and gatsby-plugin-sharp as well, and make sure they are installed and included in your gatsby-config. Also, make sure you have set up a source plugin, so your images are available in graphql queries.
Most importantly, it does not handle fallback for next-gen image formats such as AVIF and WebP. You can get the benefits of gatsby-plugin-image for background images without any extra components. This is an example of a hero image component with text overlaying an image background.
"SVG are not supported by this plugin for obvious reasons, they are vectorial and automatically adjust their size without the need of plugin like this one"
Correct. If you want to handle multiple types like png + jpg + svg you have to dynamically handle it with gatsby-image or not. You solve this by adding extension and publicURL in your GraphQL query:
...
image {
childImageSharp {
fluid(maxWidth: 500, quality: 92) {
...GatsbyImageSharpFluid
}
}
extension
publicURL
}
...
Add this to your image component:
// svg support
if (!childImageSharp && extension === 'svg') {
return <img style={imageStyle} src={publicURL} alt={alt} />
}
Credit goes to andresmrm on GitHub.
SVG are not supported by this plugin for obvious reasons, they are vectorial and automatically adjust their size without the need of plugin like this one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With