Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

import all images from folder reactjs

function importAll(r) {
  let images = {};
  r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
  return images;
}

const images = importAll(require.context('./images', false, /.(png|jpe?g|svg)$/));

<img src={images['doggy.png']} />
Comment

Import all images from folder react

// Original answer by Kind Kouprey, additional comments and integer index alternative by me.

function importAll(r) {
  
  //// Use these line if you like to access arrays using an integer index.
  //let images = [];
  //r.keys().map((item, index) => { images.push(r(item)); });
  
  ////Use these line if you want to access each image using the file name.
  //let images = {};
  //r.keys().map((item, index) => { images[item.replace('./','')] = r(item); });
  
  return images;
}

//Param 1: The path or route to the directory you want to import.
//Param 2 (optional): Include directories?
//Param 3 (optional): Use a regular expression (regex) such as "/.(png|jpe?g|svg)$/" to select only certain file types.
const images = importAll(require.context('./images', false, /.(png|jpe?g|svg)$/));

//The index can be up to the number of images in the folder - 1;
<img src={images[0]} />
<img src={images[3]} />
//Or if you used the file name method...
<img src={images["doggy.png"]} />
Comment

PREVIOUS NEXT
Code Example
Javascript :: react change background image on hover 
Javascript :: input type number max value validation 
Javascript :: let and var difference 
Javascript :: hostlistener 
Javascript :: big o notation javascript 
Javascript :: angular compnent 
Javascript :: javascript color green to red 
Javascript :: jquery onclick multiple buttons 
Javascript :: pdfjs get all the text present 
Javascript :: sticky sessions 
Javascript :: best node js orm for mysql 
Javascript :: 1 day ago javascript 
Javascript :: angular start command 
Javascript :: js validate mongodb id 
Javascript :: javascript array print all 
Javascript :: Javascript using forEach loop to loop through an array 
Javascript :: angular 8 enable routing 
Javascript :: array.push multiple 
Javascript :: javascript syntax 
Javascript :: row smaller than the container bootstrap react 
Javascript :: setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: not a number 
Javascript :: element.js 
Javascript :: lastindexof 
Javascript :: cut and paste element js 
Javascript :: setTimeout(() = { console.log(i);}, 100); 
Javascript :: npm update package.json version field by code 
Javascript :: get file extension in javascript 
Javascript :: javascript this 
Javascript :: angular map 
Javascript :: react-native-bouncy-checkbox 
ADD CONTENT
Topic
Content
Source link
Name
3+7 =