Use index.js to import multiple image assets in React
Solution 1
if you are using webpack take a look at this require. You can use require to import a file like the example below:
tree directory
-images
|_index.js
|_notification.png
|_logo.png
-pages
|-home.js
images/index.js
export const notification = require('./notification.png')
export const logo = require('./logo.png')
pages/home.js
import { notification } from '../images/'
<img src={notification} />
i hope i helped you
Solution 2
To export
default components do it like this:
export { default as Splash } from './Splash'
export { default as Portfolio } from './Porfolio'
export { default as Contact } from './Contact'
// you dont need to include the 'index' on the route, just do './' if you
// are in the same directory, but your export file must be named index.js
import { Splash, Portfolio, Contact } from './';
To export files: images, css, .svg etc, just include the file extension:
export { default as Img01 } from './img-01.png'
export { default as Img02 } from './img-02.jpg'
export { default as Img03 } from './img-03.svg'
//Call in Component.js
import { Img01, Img02, Img03 } from '../assets/img'
Comments
-
Darren Barklie almost 2 years
I have been using a pattern of collecting component files for export with
index.js
files placed in directories, for example:// index.js file in /components directory export { Splash } from './Splash' export { Portfolio } from './Porfolio' export { Contact } from './Contact'
In
Layout.js
(located in root directory) I can neatly import with one call:import { Splash, Portfolio, Contact } from '.'
I use this pattern a lot as I structure components across directories and sub-directories.
My specific question is to ask if there is any way to extend this pattern to image assets collected in
src/assets/img
? Can I place anindex.js
file in my images directory and to be able to call groups of images to a component?//index.js in /src/assets/img directory export { Img01 } from './img-01.png' export { Img02 } from './img-02.jpg' export { Img03 } from './img-03.svg' //Call in Component.js import { Img01, Img02, Img03 } from '../assets/img'
I think this should be achievable, but I can't figure out the correct syntax or modifications required to this pattern. Any code samples or recommendations for better practices are appreciated. Thanks in advance!