So in a Reactjs class component, I have an array in my state like this:
myArray: [
{ number: 1, title: 'Users', image: '../../../assets/images/website/homepage/users.png' },
{ number: 2, title: 'Clients', image: '../../../assets/images/website/homepage/clients.png' },
{ number: 3, title: 'Admin', image: '../../../assets/images/website/homepage/admins.png' },
]
and I mapped the array this way:
{this.state.myArray.map((item, index) => (
<Box key={index} className="col-sm-12">
<img src={ item.image } className="img-fluid" alt={item.title} />
<Typography variant="h4">{item.number}</Typography>
</Box>
))}
Now, everything works fine, except the image that doesn't display, I really don't understand where I'm getting it wrong.
Note that, if I copy one of the image links directly inside the src using require method, it works. Kindly help.
You can require dynamically with proper expression:
Change image to (remove ../../../assets/images/website/homepage/ and .png):
const myArray = [
{
number: 1,
title: 'Users',
image: 'users',
},
{
number: 2,
title: 'Clients',
image: 'clients',
},
{
number: 3,
title: 'Admin',
image: 'admins',
},
]
And to render at UI (add directory path and the extension inside require):
{myArray.map((item, index) => (
<Box key={index} className="col-sm-12">
<img
src={require('../../../assets/images/website/homepage/' +
item.image +
'.png')}
className="img-fluid"
alt={item.title}
/>
<Typography variant="h4">{item.number}</Typography>
</Box>
))}
Why it works?:
Webpack can understand this expression, by generating context about directory and extension, and can load all the matching modules.
I think you are missing require.
Like:
<img src={require(item.image)} />
Related
I am trying to add a carousel for my products.
I have an array of url images in product.images that i want to show individually in the carousel but when i map them like this:
<AliceCarousel autoPlay autoPlayInterval="1500">
{[product.images].map((x) => (
<img src={x} alt={x} className="medium" />
))}
</AliceCarousel>
they do not show individually but all at once like so:
How would you map so as to get each url in the array individually to be shown within the carousel? Thanks
Probably OP resolved this by now, but if you have the responsive object then you can specify when to show how many elements you would like.
const responsive = {
2000: {
items: 10,
},
1200: {
items: 5,
},
800: {
items: 3,
},
0: {
items: 1,
},
};
<AliceCarousel responsive={responsive} autoPlay autoPlayInterval="1500">
{[product.images].map((x) => (
<img src={x} alt={x} className="medium" />
))}
</AliceCarousel>
In this scenario there would be 1 item from 0px width screen to 799px
Source: https://github.com/maxmarinich/react-alice-carousel
I am trying to use a slide that shows products attributes in my app.
The products variable has the ID, NAME, DESCRIPTION, PRICE and IMAGE.
const products = [{
id: 1,
name: "Sapato1",
description: "comfort line with adaptive design",
price: "999,99",
img: "../img/hamburger1.jpg"
}, {
id: 2,
name: "Product X",
description: "Different sizes and shapes",
price: "999,99",
img: "../img/hamburger2.jpg"
}, {
id: 3,
name: "Product Y",
description: "Many different features",
price: "999,99",
img: "../img/hamburger3.jpg"
}]
Using HTML img tag with an import it is working, but I would like to have the image related to the product I am showing, as variable.
import Image from '../img/hamburger1.jpg';
<img src={Image} alt="produt1" />
but I would like to use src={product.img} instead of the src={Image} but it is not working.
This is the code I am using
{products.map((product) =>
<IonSlide>
<IonCard button={true}>
<IonCardHeader>
<IonCardTitle>{product.name}</IonCardTitle>
<IonCardSubtitle>Card Subtitle</IonCardSubtitle>
</IonCardHeader>
<IonCardContent>
<img src={Image} alt="produt1" />
{product.description}
</IonCardContent>
<IonButton expand="full" href="#" color="primary"><IonIcon slot="start" icon={cart} />R$ {product.price}</IonButton>
</IonCard>
</IonSlide>
)}
You should put your img folder along with all the pictures in the public folder. And then you can change your references to the images like img: "/img/hamburger1.jpg". That should work. Here's a working example - https://codesandbox.io/s/hungry-golick-funtz?file=/src/App.js
I have a React component and want the images to be displayed along with the name/price.
If the images are uploaded to the same folder, can you add these paths as the value for the logo key?
Right now, the images are broken.
There are no console errors or anything.
COMPONENT
const [products] = React.useState([
{ name: "Mothership", price: 10, logo: "./PHX130.png" },
{ name: "Illideph", price: 20, logo: "./PHX132.png" },
{ name: "Phoenix", price: 30, logo: "./TX15.png" }
]);
RETURN
{products.map((product, index) => (
<Product key={index} product={product}>
<img src={product.logo} alt="website logo" />
<button className="button" onClick={() => addToCart(index)}>Add to cart</button>
</Product>
))}
It depends. If you're using a resources bundler (such as Webpack), you can require it directly and the path will be set for you:
<img src={require('./image.png')} />
Note that you'll need to have an image loader enabled (file-loader for webpack).
Otherwise, the path needs to be relative to where your output javascript file is on your server. Eg, if your main.js is at /, you'll need to have the paths relative to the root of your server.
I'm trying to map through an array of objects, rendering local images, but have painfully found out that this can't be done the same way as rendering external urls, with the images not firing.
Not been able to find a solution without cheating and declaring local images declaratively - import Logo from ... - or placing the images in the public folder, which could give me cache issues down the line. I've tried image: require("") in the array but it doesn't seem to respond.
Surely this can be done dynamically? If anyone knows of a solution to the below it would really help me out.
Directory.jsx
this.state = {
categories: [
{
title: "Burgers",
image: "../../images/Burger_landing.jpeg",
id: 1
},
{
title: "Sides",
image: "../../images/Fries_main.jpeg",
id: 2
},
{
title: "Shakes",
image: "../../images/Shakes_main.jpeg",
id: 3
}
]
};
}
render() {
return (
<div className='menu__container-position'>
{this.state.categories.map(({ title, image, id }) => (
<DirectoryItem key={id} title={title} image={image} />
))}
</div>
);
}
DirectoryItem.jsx
const DirectoryItem = ({ title, image }) => {
return (
<div
className='menu__container-img'
style={{ backgroundImage: `${image}` }}
>
<h1>{title}</h1>
</div>
);
};
You should set the image URL like below
backgroundImage: `url(${image})`
Or
backgroundImage: "url("+image+")"
If images are not in a public path
backgroundImage: `url(${require(image)})`
I want to display images in the sports array using map(). but not working
<div className="row">
{this.state.sports.map(function(sport, index){
return (
<div className="col-md-3" key={index}>
<h3 className="text-center">{this.state.sports.name}</h3>
<img src={ require('./../assets/images/'+ {this.state.sports.name} +'.jpg') } width="300px" height="180px" />
<button className="btn btn-info btn-sm" type="submit" onClick={this.join_in_sport} >JOIN</button>
</div>
)
}.bind(this))}
</div>
The problem seems to lie in how you are building the pathname for your image. Same for your <h3> tag.
src={ require('./../assets/images/'+ {this.state.sports.name} +'.jpg') }
If this.state.sports is an array, and not an object, then it can't possibly have a name key. I think you meant to print the current objects name for each iteration in your map().
So try:
<h3 className="text-center">{this.state.sports.name}</h3>
<img src={ require('./../assets/images/'+ {sport.name} +'.jpg') } width="300px" height="180px" />
This is assuming your array looks something like:
[
{name: "foo"},
{name: "bar"}
]
I have encountered the same problem,
the image folder in src doesn't work.
I moved the image folder to public and it works fine.
function App() {
const moviesData = [
name: "Terminator: Dark Fate",
img: "./badboy3.jpg", //image in public folder
},
];
const movieList = moviesData.map((movie, i) => {
return <Movie key={i} movieName={movie.name} movieImg={movie.img} />;
});
return (
<div>
{movieList}
</div>
);
}
export default App;
I was following the React beginners tutorial tried to call images dynamically by importing them as variables but this simply didn't work when trying to call them in another file (App.js) using the .map() function. Code below:
import katieImg from "../images/Katie.png";
import starImg from "../images/Katie.png";
export default [
{
img: { katieImg },
star: { starImg },
rating: "5.0",
reviewCount: 6,
location: "USA",
title: "Life Lessons with Katie Zaferes",
price: 136,
},
];
So instead I had to get rid of the dynamically imported variables and put the images folder in the public folder. This worked. Code below:
export default [
{
img: "../images/Katie.png",
star: "../images/Star.png",
rating: "5.0",
reviewCount: 6,
location: "USA",
title: "Life Lessons with Katie Zaferes",
price: 136,
},
];