How to import all icons folder in ReactJS and use it dynamically?

If I use the below code to import all images from the icon folder, it says

import * as iconSrc from './icons'; 
// I have also tried import * as iconSrc from '../icons';  but get same error

const Weather = props => {

    return (

     <div className='container'>
     <div className='cards'>
     <h5 className='py-4'>
     <img src={`iconSrc/${props.icon}.png`} alt='Icon'/>  
     </h5>
     </div>    
     </div>  

    );

};

export default Weather;

I get below error:
Module not found: Can’t resolve ‘./icons’ in 'D:\weather-app\src\component’

I have below file structure
src
|
->component
->icons

Please suggest how to access dynamic icon images from the icons folder in ReactJS

You could try this…

The problem is once the file is compiled, to know how to write the source attribute such that it points to the image.

Either you load one by one the icons, or you could do:

 <img src={process.env.PUBLIC_URL+'/'+props.icon+'.png'} alt="logo" />

See this post for deeper understanding.

you can also put you icon folder inside public folder or static folder

-public/
    -- icon

then you can refer them using src="/icon/example.png"

at the end only public folder is served by react
setup



see the url of image

Thanks, @saurabhv749, I moved my icons folder to the public folder, it’s working now. When I will push my code to GitHub will it create a new public folder and remove the icons folder or it will stay there? Is this the best practice to keep the images in a public folder?

it depends on .gitignore file

/node_modules

means don’t push this(node_modules) folder while pushing to github.

Well it depends, if you have few images in whole site or single page react app
then it’s just fine.

but for big projects with many images on different pages or user generated content
this isn’t the solution in that case you have to either provide image in base 64 string format as source (stored in database on page request)
OR a link to cloud storage services like Google Firebase or AWS …

Puting files inside public or static folder are served by server when you request for home page. Imagine if you have 1000 images in public folder when user visits your site he had to wait until it receives all 1000 images in his browser then only he can see homepage of your site

1 Like

thanks for the explanation. I got your point :+1:

1 Like

happy to help :slightly_smiling_face:
you’ll be able to connect the dots with public/static once you’ll dive into backend

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.