Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render svg files with Gatsby Image?

Currently in my project I have a folder with all my svg files, the query to get them from graphql is as follows:

query AssetsPhotos {
  allFile(filter: {extension: {regex: "/(svg)/"}, relativeDirectory: {eq: "svg"}}) {
    edges {
      node {
        id
        name
      }
    }
  }
}

but unlike image files (.png, jpg, etc) I don't have the GatsbyImageData option, how could I render them if I want something like this:

 {SgvsData.map(({ image,id,title}) => (

              <GatsbyImage image={getImage(image.gatsbyImageData)} alt={title} key={id} />

          ))}

I tried options like publicUrl, children and childImageSharp, but the image doesn't render. Thank you very much in advance

like image 894
Jhonny Carvajal Perez Avatar asked Sep 15 '25 17:09

Jhonny Carvajal Perez


2 Answers

You can query the SVG via publicURL but you can't render it using GatsbyImage. So just use the <img> tag, and you don't need a plugin.

query MyQuery {
  allFile(filter: {extension: {in: "svg"}}) {
    nodes {
      publicURL
    }
  }
}

And than to render it:

<img src={...publicURL} alt=""/> 
like image 153
Rwzr Q Avatar answered Sep 18 '25 09:09

Rwzr Q


You can't render SVG files with Gatsby Image, but you don't need to.

You could use gatsby-plugin-svgr-loader (I like it more than gatsby-plugin-react-svg but they do essentially the same):

import Icon from "./path/assets/icon.svg";

// ...

<Icon />;

In this case the plugin is configured to process svg files from a path matching /assets/

{
    resolve: 'gatsby-plugin-svgr-loader',
    options: {
        rule: {
          include: /assets/
        }
    }
}

The other way around is to write svg code directly in your component:

<svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
  <path strokeLinecap="round" strokeLinejoin="round" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
</svg>

The above example is a bell icon exported as jsx from heroicons

like image 37
Massick Avatar answered Sep 18 '25 10:09

Massick