Jryke
Jryke

Reputation: 148

path to svg not working with img tag in Gatsby

I am trying to use svg images that I can pass as props (I will be using an array of svg images). I am using gatsby-plugin-react-svg which allows me to import the svg and use it as a component. This works but I can't pass the svg images as props or reference them in an array this way. While looking for a solution I have seen many suggestions to import the svg and then use it as the src in an img tag. This would work perfectly for me but it doesn't work when I try it. Do I need a different plugin to use svg images this way?

This works (which also means that my path is correct):

import CurrentSelected from "../assets/markers/current_selected.svg"

<Layout>
  <CurrentSelected />
</Layout>

These don't work (but is what I need to use):

import CurrentSelected from "../assets/markers/current_selected.svg"

<Layout>
  <img src={CurrentSelected} />
</Layout>

OR

<Layout>
  <img src={require("../assets/markers/current_selected.svg")} />
</Layout>

While looking for a solution, I have seen this suggested as a solution but it doesn't work in my project. Can anyone help me to render my images this way (or any other way that's not using the svg as a component)?

Upvotes: 2

Views: 1750

Answers (2)

Jryke
Jryke

Reputation: 148

I resolved this a little while ago, I just wanted to follow up on my own question in case anyone else has this same issue.

The issue was that gatsby-plugin-react-svg converts the SVG files into React components so the path was returning a React component, not an SVG file. To fix it, I had to remove the gatsby-plugin-react-svg and after that it worked fine.

Upvotes: 2

Ferran Buireu
Ferran Buireu

Reputation: 29335

This works (which also means that my path is correct):

Not necessarily , the path when importing from the SVG is inferred by webpack sourcing from the plugin (gatsby-plugin-react-svg) and may differ when importing assets directly. Check the relativity of your paths:

import CurrentSelected from "./src/assets/markers/current_selected.svg"

<Layout>
  <img src={CurrentSelected} />
</Layout>

Upvotes: 0

Related Questions