How to do Dynamic images in ReactJS? - reactjs

In my system I have a few images that a user can have presented and it's extremely advantageous to me to be able to just pass in an id and then have that image be presented to the user.
(One use case: Articles in the system have images associated with them, there are many articles in the system, it'd be ideal to pull out just the image-id and have the image dynamically displayed based upon that id. There is no realistic possible way I can statically give an image path for each article.)
Unfortunately I've tried to figure this out and haven't gotten far at all. I'd be super-duper appreciative of a "Explain it to me like I am 5" answer on this one.
I have been trying to use images in two different ways and both have unfortunately not worked at all for me. Where unfortunately I am going to need both to continue :(
1: Putting it as a background of a div. [I am using it as a carousel with overlaying text here.]
2: Putting it as just a standalone image. [This is going to make up the 95%+ case of image use through the webapp.]
I'd love to in a perfect world just pass in an object like this to props.
articleDetails = {
articleId: 38387,
articleTitle: "Magical Unicorn Article"
articleContent: "I am not that creative, but here is some content."
}
<IndividualArticle article={articleDetails}/>
Then for props to take this in and convert it into the image path to my local files.
templateStringForImage = `../../../../articleImages/${this.props.article.articleId}.png`
Then for this template string to be used as:
1: the background image of a div
<div
className="container"
style={{
backgroundImage: `url(${templateStringForImage})` ,
height: "576px"
}}
enter code here
</div>
2: standalone image
<Image
src={require({templateStringForImage})}
/>
Some of the things I've tried:
I've tried a few changes like changing the code around to be like:
var Background = `../../../images/articleImages/${
this.props.article.image
}`;
​
<div style={{
backgroundImage: url('../../../images/articleImages/article3Image.png'),
height: "576px"
}}
But unfortunately that only gave me these errors.
Line 32: 'url' is not defined no-undef
Also when I went to try and use the new Background object like this I got a different error
var Background = `../../../images/articleImages/${
this.props.article.image
}`;
<Image
src={require({Background})}
/>
The error was:
Error: Cannot find module '[object Object]'
My current system/errors:
-I have a bunch of images like article1Image.png, article2Image.png, article3Image.png specified in the src code in an image folder.
-I want to pass "article1Image.png" into the object directly and have an image produced.
-I tried to do something like this and it has consistently failed, I don't even get an error message when I attempt to use it as a backgroundImage on a div unfortunately... it's literally just blank space on my screen. No broken image icon, just a void.
var Background = `'../../../images/articleImages/${
this.props.article.image
}'`;
<div
style={{
backgroundImage: `url(${Background})`,
height: "576px"
}}
-When attempting to use semantic-ui's Image I am also running into a nasty error
<Image
src={require(Background)}
/>
Error:
Error: Cannot find module ''../../../images/articleImages/article2Image.png''
Yet shockingly enough THIS works, when I give it as a static string like this.
<Image
src={require('../../../images/articleImages/article2Image.png')}
/>
But even when I give the string path directly into the backgroundImage of the div it still appears empty...
<div
style={{
backgroundImage: `url(../../../images/articleImages/article3Image.png)`,
height: "576px"
}}
Thanks all I truly appreciate the help lots and lots!

There are 2 different solutions based on what you have tried.
URL
If you want to access them via style={{ backgroundImage: 'url(...)' }}, the url will need to be accessible from the front-end. If you used create-react-app, that would mean placing images in the public folder instead of the src folder.
So if you had images in the public folder like: /public/articleImages/article2Image.png, you could use the url style attribute:
const imageName = 'article2Image.png';
<div style={{ backgroundImage: `url('/articleImages/${imageName}')` }}>
...
</div>
<img src={`/articleImages/${imageName}`} />
If you aren't using create-react-app config, then you will need to make the images available via however you are serving your application (i.e. express).
Require
This one is a little tricky, and I'm not 100% why it doesn't work out of the box.
What I had to do when testing this was to require all of my images at the top of the file, hard-coded, and then I was able to use the require(stringTemplate) just fine. But I was getting a Error: fileName hasn't been transpiled yet., so I'm not sure if the same fix will work for you.
It basically looks like this:
require('../../../images/articleImages/article1Image.png');
require('../../../images/articleImages/article2Image.png');
...
// This code would be inside a component
const imageName = 'article2Image.png';
const filePath = '../../../images/articleImages/${imageName}';
const fileUrl = require(filePath);
<div style={{ backgroundImage: `url(${fileUrl})` }}>
...
</div>
<img src={fileUrl} />
Without the require(s) at the top of the file, something goes wrong with transpilation.
My suggestion would be go the static assets route which would allow you to use the URL technique above. require is more suited to static files that don't change often like icons.
Feel free to ask any questions, and I'd be happy to clarify and give more examples.

Related

Not displaying Background image at the time of Build in React js

Hi my app running good at localhost but when I create build then Background image not displaying.
my code is.
<div style={{ backgroundImage:"url("+require("assets/img/bg.jpg")+")", height: "400px",
backgroundSize: "cover",
backgroundPosition: "center top"}}>
Result at localhost as below
But at live server empty header with path
When I inspect this path then showing like this.
background-image: url(./static/media/bg6.488bc24….jpg);
Please help with thanks
You can try importing the image outside of the function instead of requiring it.
PS:- You can kindly attach a SS of your build folder for further info.
Perhaps, upon build, programmatically defined path is being changed or appoints to an undesired resource.
You could try to modify your DOM and apply css, by adding a dedicated tag, like so:
<img
id="background-image"
src="./assets/img/bg.jpg"
alt="background-image"
/>
Put your file to public folder and replace require with string with path.
For example put file to public/assets/img/bg.jpg
And change path:
{
backgroundImage: "url(/assets/img/bg.jpg)"
...
}
or you can use import and put imported image to img (src prop).

Raect and tailwindcss Div Background

I wish you had a good day till now,
I have a json file in my project which contains the name of the images that I want to be the background of my divs. The Problem is I can't go trough the name with function when i use tailwindcss (I mean in the className I can't put function to put the name in the url one by one) because I use this way:
<div className="bg-[url('./asset/image/1.jpg')] " >
I Also tried the style way but in this way the image won't show up (I have no Idea why):
<div style={{ backgroundImage: `url('${value.background}')` }} />
I would appreciate your help :)

Display a local image in reactjs doesn't work

The task is simple: display a local image in a reactjs app based on dynamic data.
This is what I tried (assume path_to_image is derived dynamically):
<img src={require(path_to_image} />
generates an error:
Error: Cannot find module '../../images/logos/somelogo.jpg'
Without the require:
<img src={path_to_image} />
generates a broken image.
These two methods seem to be what people are doing, but no luck here. How do I solve this?
import image from "./path/to/image.png"
If you plan using more images in a dynamic way maybe you should store their paths in a db and then query the db for the respective path. Actually that's how it's done with a CMS for example. Even if you store the files on the same hosting, you would still save their paths to a DB instead of hardcoding.
Use this:
import SomeLogo from '../../images/logos/somelogo.jpg';
You can then use it like this:
<img src={SomeLogo} />
As for multiple images, you could store them in a JSON array, and then loop through them and add each image.
This does it:
let imageSrc = require("../../images/logos/generic.jpeg");
let dynamiclyGeneratedSrc = ...;
if (dynamiclyGeneratedSrc !== undefined) {
imageSrc = require(`../../images/logos/${dynamiclyGeneratedSrc}`);
}

Render ReactJS - './images/0.jpg' works.. but property.image doesn't?

In a render (returned from a function), I have:
{console.log(property.image)}
{console.log(typeof property.image)}
<Image src={require('./images/0.jpg')} fluid rounded />
Which renders the image correctly and console logs "./images/0.jpg" string
But when I try:
{console.log(property.image)}
{console.log(typeof property.image)}
<Image src={require(property.image)} fluid rounded />
I get:
Error: Cannot find module './images/0.jpg',
which doesn't make sense to me...
Also, I am unsure how to assign variables in render, I tried :
{ var abc = property.image }
but get:
./src/App.js Syntax error: Unexpected token (220:12)
If someone can help me understand why, I would greatly appreciate it.
I'm assuming you are using web pack or something similar (create react app or parcel, for instance). That's (usually) where the require function comes from, and why you can 'require' an image. But the only images you can require are local ones (images in your project source), not images on the web.
If you want to get an image from the web, require is not what you want. In that case, you just pass the url as a string to the src property.
However, if you do need images that are in your project source, then you would probably use require. Most of the time, you use require at the top of a file, and pass it a string, not a variable. This is because your packager reads the file before packing it up, and looks for any requires, so that it can include them in the package. But when you pass require a variable, it can't do that. However, you can use require.context if you want to load files dynamically from a directory.
So you probably want this at the top of your file:
const pathToImages require.context('./images', true);
and in your render:
<Image src={pathToImages('0.jpg')} fluid rounded />
or
<Image src={pathToImages(property.image)} fluid rounded />

Images are not found when styling background using URL to locate image in react

I am learning react, hence I am new to react though not new to development. I was creating a slider in which the <div> have a background that is to be set using already present images. I think there is mistake somewhere in dynamically allocating the directory of the images although i am not entirely sure.
This is short image of directory
image of directory
I have details of images stored in a const slides in which cover holds the name of image( like cover1.jpg). When I console.log(item.cover) I got the correct names of images, but I can't seem to implement it to correctly represent the directory of images
This is the current code that is written in featured.js
slides.map((item)=>{
return(
<div key={item.id} className="item-slider"
style={{background:'url("../images/covers/'+item.cover+'")'}} >
</div>
)
})
And previously i have tried
style={{background:'url(/images/covers/${item.cover})'}}
and
style={{background:'url("images/covers/${item.cover}")'}}
with many different combos of directory
How can i get the images to show and what am i doing wrong. Any help is well appreciated.
You're not using template literals correctly. You're using ' instead of `.
style={{background:`url(/images/covers/${item.cover})`}}
I don't Know Why! but it worked when i added another nest
slides.map((item)=>{
return(
<div key={item.id}>
<div className="item-slider"
style={{background:'url("../images/covers/'+item.cover+'")'}} >
</div>
</div>
)
})

Resources