React svg from public folder
Asked Answered
M

3

6

I'm trying to import the svg from the public folder.

How can I do that using import?

I've tried:

import Avatar_1 from './public/avatar_1.svg';

but I'm still getting "Module not found: Can't resolve './public/avatar_1.svg'"

Is there a way to use process.env.PUBLIC_URL?

Mccollum answered 29/11, 2019 at 12:48 Comment(0)
M
9

I think it's not possible to access the public folder from src, so I did the following:

import { ReactComponent as Avatar1 } from './assets/avatar_1.svg';

and it worked.

How to use it:

<Avatar1 />

Please note that the ReactComponent as part of the import is mandatory, and that your new component name, like Avatar1, should always start with a capital letter. Otherwise react won't recognize this as a react component.

Mccollum answered 5/12, 2019 at 7:26 Comment(0)
D
0

Create 'icons' folder in Public Directory and Use this code :

import React, { Component } from 'react';    
const iconPath = process.env.PUBLIC_URL + '/icons/';

export default class TestComponent extends Component {
constructor(props) {
    super(props);
}
render(){
return (<img
    src={`${iconPath}icon-arrow.svg`}
    alt="more"
/>)
}
}
Doscher answered 29/11, 2019 at 12:58 Comment(1)
Thanks but I would like to use import as a React Component and then use <Avatar_1 />Mccollum
F
0

I don't know why you want to import it this way,

You can use it inside <img /> tag like this:

export default function MyComponent() {
   return (
      <div>
         <img src='/logo.svg' widt={100} height={100} />
      </div>
   );
}
Foremost answered 5/10 at 11:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.