Josh
Josh

Reputation: 1235

React: Trying to create separate folder for SVGs and import them into my components but unsure of how to import

I have a folder called Assets in the src directory of my application where I'm attempting to host SVGs and then import them into my components but I'm at a loss for how to do this. I've included my SVG file below as well as my attempt to import it into my component right beneath it. Any help is hugely appreciated

SVG file

<svg fill="black" viewBox="0 0 320 512" height="1.5rem" width="1.5rem" xmlns="http://www.w3.org/2000/svg">
    <path d="M31.3 192h257.3c17.8 0 26.7 21.5 14.1 34.1L174.1 354.8c-7.8 7.8-20.5 7.8-28.3 0L17.2 226.1C4.6 213.5 13.5 192 31.3 192z"></path>
</svg>

Import statement in React Component trying to import SVG

import {icon} from '../../assets/caretDown'

Upvotes: 0

Views: 1634

Answers (1)

Shubham Verma
Shubham Verma

Reputation: 5054

You have to import file like this including svg extension. For example :

import icon from '../../assets/caretDown.svg'

You have to mention extenstion name as well. If you want to import multiple image then you can create one index.js file in assets folder which hold all assets image. For ex :

import icon from 'caretDown.svg'
import iconUp from 'caretUp.svg'

Then you can export these as

export{icon,iconUp}

Then whenever you required these images somewhere in file. You can directly import like this:

import {icon} from '../../assets/'

Ex : https://codesandbox.io/s/svg-in-react-s6u32

Upvotes: 2

Related Questions