Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React svg from public folder

Tags:

reactjs

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?

like image 657
NikNik Avatar asked Sep 07 '26 23:09

NikNik


2 Answers

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.

like image 75
NikNik Avatar answered Sep 11 '26 02:09

NikNik


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' width={100} height={100} />
      </div>
   );
}
like image 25
walid Avatar answered Sep 11 '26 01:09

walid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!