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 :: how to submit form using ajax 
Javascript :: node js return json 
Javascript :: javascript extract hour from string 
Javascript :: how to get datetime javascript now 
Javascript :: toggle button by javascript 
Javascript :: latitude and longitude distance calculate in node js 
Javascript :: datatable get all selected row data 
Javascript :: target url javascript 
Javascript :: truncate a string 
Javascript :: datatables integration 
Javascript :: readonly vs disabled 
Javascript :: js how to print 
Javascript :: react save to local storage 
Javascript :: javascript try catch 
Javascript :: javascript get elements that exist in two arrays 
Javascript :: node js send fcm 
Javascript :: xmlhttprequest pass parameters post 
Javascript :: kb to mb js 
Javascript :: on click button change route next js 
Javascript :: req body express 
Javascript :: ajax load document ready 
Javascript :: logout user firebase 
Javascript :: array reverse algorithm in js 
Javascript :: credit card regex 
Javascript :: javascript take first element of array 
Javascript :: js json stringfy beutify 
Javascript :: js find longest word in string function 
Javascript :: javascript input checkbox name 
Javascript :: event.target data-target 
Javascript :: semantics ui complete responsive menu 
ADD CONTENT
Topic
Content
Source link
Name
2+7 =