Import multiple images on React - javascript

I'm trying to build a react app and I have to use multiple images
,now do i have to import every images i'll use like:
import image from '/img/img1.png';
<img src={img} />
or is there another way to it???,
PS: I've tried "require" and it gave an error also :
<img src={windows.location.origin +'/img/img1.png'}/>
gives no output

Since you are using webpack, have a look at require.context . You should be able to import all png files in '/img' to images variable. Then you can use image by images["img(n).png"].
function importAll(r) {
let images = {};
r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
return images;
}
const images = importAll(require.context('/img', false, '/\.jpg/'));
<img src={images["img1.png"]} />
In another way, you can use a file dedicated to these imports :
images.js :
import img1 from "/img/img1.jpg"
import img2 from "/img/img2.jpg"
import img3 from "/img/img3.jpg"
.
.
.
import img(n) from "/img/img(n).jpg"
export default [
img1,
img2,
...
];
Then import this array in one line in other files :
import imgs from './images';
P.S. please refer my accepted answer on similar question.

If you're using ES6+, you can use iteral. Something like below.
const imageNames = ['img1.jpg', 'img2.jpg', 'img3.jpg']
render() {
...
imageNames.map(image => <img src={`/img/${image}`}></img>)
...
}

instead of using array [] as mentioned #koko-js478 export js like this:
icons.js:
import animals_for_sale from '../Assets/icons/animals_for_sale.svg';
import baby_toys from '../Assets/icons/baby_toys.svg';
import cars_and_vehicles from '../Assets/icons/cars_and_vehicles.svg';
import contact_us from '../Assets/icons/contact_us.svg';
import devices from '../Assets/icons/devices.svg';
import electronic_appliances from '../Assets/icons/electronic_appliances.svg';
import fashion from '../Assets/icons/fashion.svg';
import home_and_garden from '../Assets/icons/home_and_garden.svg';
import homepage_icon from '../Assets/icons/homepage_icon.svg';
import login from '../Assets/icons/login.svg';
import my_account from '../Assets/icons/my_account.svg';
import privacy_policy from '../Assets/icons/privacy_policy.svg';
import real_estate_for_rent from '../Assets/icons/real_estate_for_rent.svg';
import real_estate from '../Assets/icons/real_estate.svg';
import services from '../Assets/icons/services.svg';
import use_app from '../Assets/icons/use_app.svg';
export default {
'animals_for_sale':animals_for_sale,
'baby_toys':baby_toys,
'cars_and_vehicles':cars_and_vehicles,
'contact_us':contact_us,
'devices':devices,
'electronic_appliances':electronic_appliances,
'fashion':fashion,
'home_and_garden':home_and_garden,
'homepage_icon':homepage_icon,
'login':login,
'my_account':my_account,
'privacy_policy':privacy_policy,
'real_estate_for_rent':real_estate_for_rent,
'real_estate':real_estate,
'services' :services,
'use_app':use_app
};
and then import a hole json like this:
import icons from './icons';
after that you can use every single icon like this:
<li><a className='dropdown-item'><img src={icons.cars_and_vehicles} className="img-section"/>Voitures et véhicules »</a>

maybe this can help you
function importAll(r) {
let images = {};
r.keys().forEach((item, index) => { images[item.replace('./', '')] = r(item); });
return images
}
const images = importAll(require.context('../assets', false, /\.(png|jpe?g|svg)$/));
know more from here

Related

Problem when importing from another folder in React Typescript

I have the following folder structure
I want to import both MessageList.tsx and MessageSent.tsx inside my Chat.tsx
// Chat.tsx
import React from 'react'
import {MessageList, MessageSent} from "./components/"
type Props = {}
const Chat= (props: Props) =\> {
return (
<div\>Chat</div>
)
}
export default Chat`
// MessageSent.tsx
import React from 'react'
type Props = {}
const MessageList = (props: Props) => {
return (
<div>MessageList</div>
)
}
export default MessageList
MessageList.tsx is similar to MessageSent,tsx, only the name of the components is different
However, when I try to do the import of these two components {MessageList, MessageSent} I get the following error:
** Cannot find module './components/' or its corresponding type declarations.**
Why is that?
Tried different paths besides "./components/", even with full path.
You can either import the components one by one
import MessageSent from "./components/MessageSent"
import MessageList from "./components/MessageList"
or create an index directory file (index.ts)
import MessageSent from './MessageSent'
import MessageList from './MessageList'
export { MessageSent, MessageList }
To be able to import from components you need index.ts file in components folder.
// index.ts
export * from './MessageList';
export * from './MessageSent';
Add a new file named index.ts inside your components folder
Then write this in the index.ts
export * from './MessageList.tsx';
export * from './MessageSent.tsx';

How can we import the image from one js file to another js file

I am trying to import the image from one js file to another js file.
My first js file is as function component Track.js
import React from 'react'
import { screenimage, screenimage1 } from "./srcimages.js";
function Track() {
return (
<div>
Hello Component
<img src={screenimage} alt=""/>
<img src={screenimage1} alt=""/>
</div>
)
}
export default Track
My second js file is as const image.js
const screenimage = 'https://image.shutterstock.com/image-illustration/shopping-online-concept-modern-design-260nw-1934432345.jpg';
const screenimage1 = 'https://www.publicdomainpictures.net/pictures/320000/velka/background-image.png';
I am trying to make a collection of multiple image source in one js file and import it as img <img src={here}/> attribute. I tried the above method but it's showing empty value of src.
UPDATE
Remove the tag "typoscript" from this post
You need to export the images from the image.js file. Check the code below:
export const screenimage = "https://image.shutterstock.com/image-illustration/shopping-online-concept-modern-design-260nw-1934432345.jpg";
export const screenimage1 = "https://www.publicdomainpictures.net/pictures/320000/velka/background-image.png";
So try add the export behind the const
like
export const screenimage = 'https://image.shutterstock.com/image-illustration/shopping-online-concept-modern-design-260nw-1934432345.jpg',

Export function not working in JavaScript

I have been working on a shopping list application in React but have ran into a problem with exporting a regular JavaScript function from a file called webscrape.js into my react App.js I have tried multiple different ways of exporting but I keep getting this error.
Thanks to any help in advance.
Module not found: Can't resolve 'readline' in
'C:\Users\USERNAME\Desktop\Programming-Projects\Counter
App\counter-app\node_modules\puppeteer\lib\cjs\puppeteer\node'
This is the end of my webscrape file where I export a test function
function testExport(){
console.log("Test Export");
}
function testExport2(){
console.log("Test Export 2");
}
export {testExport, testExport2}
This is the start of my App.js where I import and try using the function
import NavBar from "./components/navbar";
import PriceBar from "./components/pricebar";
import "./App.css";
import Counters from "./components/counters";
import fs from 'fs';
import data from "./shoppingData.json";
import {testExport, testExport2} from "./webscrape.js";
//test export
testExport();
You should use export default {testExport, testExport2}.
But, looking throught your errors, seems like the error it's related to puppeter. Do you have puppteer added to your node_modules? Did you make a npm i?
Try:
export const testExport = () => {
console.log("Test Export");
}
export const testExport2 = () => {
console.log("Test Export 2");
}

Exporting entire CONST js

I have a separate JS file containing all my constants:
export const LABEL_1 = "Hello there"
export const LABEL_2 = 'Hi Madame'
export const LABEL_3 = 'Hello Sir'
I used to import all of them as:
import * as CONS from 'path/to/fileWithConstants'
Then access them as:
console.log(CONS.LABEL_1)
However, for simplicity, I prefer not to reference "CONS" anymore. So I did the import like this:
import { LABEL_1 } from 'path/to/fileWithConstants'
console.log(LABEL_1)
But I do not want to put each and every constant in the import line.
How can I import the entire file with all these constants (there are hundreds of them) without having to reference CONS??
Thanks!
How about exporting them with a spread?
import * as CONS from 'path/to/fileWithConstants'
export {
...CONS,
}
In separate JS file use something like
export default {
LABEL_1: "Hello there",
LABEL_2: "Hi Madame",
LABEL_3: "Hello Sir"
};
Import this file as
import CONS from "./modules/testing";
console.log(CONS.LABEL_1)

How to Export Variables with a Dynamic Names

I have a components folder in nuxt.js
/components/atoms/
and inside that folder I have an index.js to export all components dynamically
const req = require.context('./', true, /\.vue$/)
const components = {}
req.keys().forEach(fileName => {
const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
components[componentName] = req(fileName).default
})
export const { ButtonStyled, TextLead, InputSearch } = components
so I can import perfectly as I wish
import { ButtonStyled } from "#/components/atoms"
the problem is that I am defining the variables to be exported statically, fixed, so for each created component I would need to add another variable manually
I need to dynamically export the variable name
Example:
DynamicCreation = ['ButtonStyled', 'TextLead', 'InputSearch']
export const { DynamicCreation } = components
// output -> export const { ButtonStyled, TextLead,InputSearch } = components
I need to export the name of already unstructured variables
Note: I can not use this export default components because I can not import like this import { ButtonStyled } from "#/components/atoms"
You should be able to do it like this:
export default components
Then in your file where you want to use the components:
import * as components from '#/components/atoms'
Then when you need to use the components in your Vue files, you need to map them:
#Component({
components: {
ButtonStyled: components.ButtonStyled
}
})
And now you have:
<ButtonStyled></ButtonStyled>
You can make something like this way, check if is what do you need.
Create a file to import a conjunct of components: allComponents.js
export default {
componentOne: require('./passToOneComponent.js');
componentTwo: require('./passToOneComponent.js');
componentThree: require('./passToOneComponent.js');
}
After in index.js export the allComponents.js with the name that you wish:
export {default as SomeName } from 'allComponents.js';
So in the final file, you can make something like:
import { SomeName } from 'index.js';
SomeName.componentOne();
I created a library that does this type of export, anyone who wants can install via npm
I created a Webpack Plugin that makes named exports from a component, maybe this helps other people
Weback Plugin - named-exports

Categories

Resources