Displaying images with webpack using require.context - reactjs

I have made my first React app using Webpack with the create-react-app tool.
I have an unknown amount of images in a folder I would like to display as my apps background at random. Using some code from the Webpack docs and other threads I use this code in my component.
import React, { Component } from 'react';
import './styles/css/App.css';
function requireAll(r) {
r.keys().forEach(r);
var images = r.keys();
images = images.map( path => "./images/backgrounds/" + path );
console.log(images);
return images;
}
var images = requireAll(require.context('./images/backgrounds/', true, /\.jpg$/));
let randomIndex = Math.floor(Math.random() * images.length) + 0;
var randomImgRef = images[randomIndex];
class App extends Component {
render() {
return (
<div className="App" style={{backgroundImage: "url(" + randomImgRef + ")"}} >
<h1>hi</h1>
</div>
);
}
}
export default App;
This seems to work, the background style has the right path and my console logs the right path also. But no images are displayed, and I'm clueless.
I think Webpack might not be including the images in the build, though the code I'm using seems like it should do that. So I'm clueless.
Any ideas?

I think for your example you just have to use randomImgRef.default so use the default property to get the url.
EXAMPLE Using require.context to display images:
const photos = importAll(require.context('../../assets/photos', false, /\.(png|jpe?g|svg)$/));
Render:
<div>
{photos.map((photo, i) => (
<div className="photo" key={i}>
<img src={photo.default} alt=`photo-${i}` />
</div>
))}
</div>

Related

Why local svg icons not resolve in react.js projects?

I have local icons, and I add icons in build folder like screenshot below, then I was import icons like that import {ReactComponent as MyIcon} from "build/icons/my-icon.svg";, but still say "Can't resolve 'build/icons/my-icon.svg'", any idea?
Screenshot:
you need to use file-loader
and when you import dont use brackets since its default export just chose the name directly
import myIcon from "build/icons/my-icon.svg";
const App = () => {
return (
<div className="App">
<img src={myIcon} />
</div>
);
}
Svg tag
second option would be to extract the svg tag and put it directly into you component ,
const App = () => {
return (
<div className="App">
<svg .... // copy the content of your .svg
</svg>
</div>
);
}

How to dynamically render images in react?

How to dynamically render/ import images in react / typescript?
I'm using Typescript with React.
Following is what I want to achieve.
but this is not working. It is not resolving the expression { 'assets/icons/' + media + '.svg'} .
<div className="medias">
MEDIAS.map((media) =>
(<img src={ 'assets/icons/' + media + '.svg'} />)
)
</div>
This is what I've tried.
const Medias = async () => {
return (
<div className="medias">
{await Promise.all(
MEDIAS.map((media) =>
import(`assets/icons/${media}.svg`).then((v) => v.default)()
).map((item) => <img src={media} />)
)}
</div>
);
};
export default Medias
I want to dynamically import and render images based on the above logic.
In angular or vue this can be achieved easily inside templates. But here in react it seems like not working.
But seems like it is not working.
Is there a work around?
For local image files instead of importing every image while mapping over them, you can make a separate file and add all the imports in that file and make an object of all the images, and export that object to use anywhere dynamically. I have created an example on the sandbox here you can check this out for your case.
import img1 from "./assets/1.jpeg";
import img2 from "./assets/2.jpeg";
import img3 from "./assets/3.jpeg";
export const imagesPath = {
img1: img1,
img2: img2,
img3: img3
};
Now, this can be used to dynamically use the images as shown in the code snippet below.
Medias.map((media) => (
<img
src={imagesPath[media]}
alt="Dynamic Image"
key={media}
/>
))
To see the working example checkout the code sandbox link given above.

can't Load local files dynamically in react js

I want to load some local images dynamically in my app. I have a json with records like
{name: image12, poster: 'image1.jpg'}, {name: image13, poster: 'image2.jpg'}
I have a folder with many images like 'image1.jpg', 'image2.jpg', 'image3.jpg'. When I try to render the json record i put
<img src={'./image/image1.jpg'}/> but it is not working.
[![import React from 'react';
const Poster = (props) => {
return(
<div className="individual-poster">
<h2>{props.postData.name}</h2>
<img src={'./Slices/'+props.postData["poster"]} width="100px" height="100px"/>
</div>
);
}
image is not even listing in the source list also.
if you know path images then your json object you trying to map must be somewhat similar to this:
const obj = [
{"name":"Chrysanthemum","path":require('./Chrysanthemum.jpg')}, //this will work
{"name":"Desert","path":'./Desert.jpg'}, //will not work
]
require your path to images must be inside require mehtod.
Use like considering json obj file exported as default in same directory with file name imagesJson.
import imagArray from './images';
map like this
imagArray.map((m)=>{
return <div>
{m.name}
<img src={m.path}/>
</div>
})
If you created you react app with create-react-app then you can import image variable and later use it multiple time.
import logo from './logo.png' // relative path to image
class App extends Component {
render() {
return (
<img src={logo} alt={"logo"}/>
)
}
}
or you can directly specify image relative path.
<img src ="http://localhost:3000/img/foo.png" />
<img src="/details/img/bar.png" />
In your question for use images from array
const images = [{
name: 'image12',
path: 'image1.jpg'
}, {
name: 'image13',
path: 'image2.jpg'
}];
class App extends Component {
render() {
return (
<div>
<img src={logo} alt={"logo"}/>
{images.map((img) => <img src={img.post} alt={img.name} />)}
</div>
)
}
}

React - Inline CSS and Image won't load

I'm still new to React and after I finished the tutorial I wanted to create something myself.
I've passed the url to make a backgroundImage style and add borders to try it out. Unfortunately I can see the img being set in the css but it won't actually display as expected.
As a test I also tried a simple img with src attribute set to my image and nothing would display.
I made a folder called img inside the src
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<Home/>
</div>
);
}
}
function Portfolio(props) {
const stylee = {
backgroundImage:'url('+props.imgURL+')',
borderWidth: 1,
};
const ide = 'portfolio'+props.counting;
return (<div id={ide} style={stylee} className='portfolio'/>)
}
class Home extends Component {
renderPortfolio(count,img){
return <Portfolio counting={count} imgURL={img}/>
}
render(){
return(
<div>
{this.renderPortfolio(1,'./img/1.jpeg')}
{this.renderPortfolio(2,'./img/2.jpeg')}
{this.renderPortfolio(3,'./img/1.jpeg')}
<img src='./img/1.jpeg'/>
</div>
)
}
}
export default App;
What am I doing wrong that is preventing the images from displaying ?
edit-- I've changed my code to the working solution
Instead of passing the local img url, I used require() first then pass the image to props.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<Home/>
</div>
);
}
}
function Portfolio(props) {
const counter = 'portfolio'+props.counting;
const loadGambar = props.gmbr;
// const loadGambar2 = require(props.gmbr);
const stylee = {
borderColor:props.color,
border:1,
borderWidth: 10,
backgroundImage: "url("+loadGambar+")",
}
return(
<div id={counter} className='portfolio' style={stylee}>
</div>
)
}
class Home extends Component {
renderPortfolio(count,gambare){
return <Portfolio counting={count} gmbr={gambare}/>
}
render(){
return(
<div>
{this.renderPortfolio(1,require('./img/1.jpg))}
{this.renderPortfolio(2,require('./img/1.jpg'))}
{this.renderPortfolio(3,require('./img/2.jpg'))}
</div>
)
}
}
export default App;
Here's a link to a working example based on your code: sandbox link.
The problem with setting a background image is that it adapts to the dimensions of the div. In your case your div is empty in Portfolio so its dimensions are 0x0 and the image won't show. You will see from the link that I update the style and everything shows. Now the only issue you might have is that you don't have an image loader in your webpack configuration, if you are starting with react I would recommend create-react-app.

Why Images not loading, when trying to load from an array in react

I have following code where i am trying to load images from Array, if i try to load a single image it works fine, but if i try to load multiple images it dosent show any image, tho my div test is in the dom.
import React, {Component} from 'react';
class Slider extends Component {
render() {
const myItems = [{source_image: '1.jpg'}, {source_image: '2.jpg'}, {source_image: '3.jpg'}];
return (
<div id="test">
{myItems.map(function (a) {
<img src={"images/"+a.source_image}/>
}
)}
</div>
);
}
}
export default Slider;
You forget return in map:
{myItems.map(function (a) {
return <img src={"images/"+a.source_image}/> // here
})
}
{myItems.map(a => <img src={"images/"+a.source_image}/>)} //this is more clear, I think

Resources