Image not getting rendered in react application - reactjs

Unable to render images in react, In browser console, image names are displayed correctly but on UI it is not displayed. Also, src attribute is missing from img tag after inspecting element. Please assist. Here is Sample Script
function importAll(r) {
let images = {};
r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
return images;
}
const get_images = importAll(require.context('../../images', true, /\.(png|jpe?g|svg)$/));
const images = Object.entries(get_images).map(module => module[1].default);
return (
<div className="product">
<div>
<Row>
{products.map(product =>
<Col span={6} key={product.productId}>
<div >
<div>{console.log(product.productImageName)}
{<Image src={images[product.productImageName]} width={200}
height={200} />}
</div>
</div>
</Col>
)
}
</Row>
</div>
</div>
)

You don't need to import images. if images are part of your repository then you can use the relative path from the src directory. e.g assuming the images in under src
const path = `images/${[product.productImageName]}`;
<Image src={path} />

You should try and check if profile exist. Like this:
{profile && profile.map((...
//Or
{profile?.map((...

Related

React is not dynamically loading images

I am trying to dynamically load images in a map function but it won't return anything.
I can get it to load a single image if I import it at the top of the page and hardcode the src but I have tried every solution I can find to do it dynamically and none of them work.
Here is what the code looks like. I am passing props with the title of the PNGs but nothing will load.
const Project = (props) => {
const proj = props.proj
return (
<div >
{proj.map(({title, id}) =>{
return(
<div>
<div className="..." key={id}>
<img
src={require(`../Assets/${title}.png`).default}
alt={`Image of ${title} hompage`}
className='object-cover'
/>
</div>
</div>
)
})}
</div>
)
}
export default Project;
The app was set up with create react app. I tried setting up a library but it didn't load the images either.

Append slides dynamically in Swiper slider in React

I am creating a new application in React. I want to use the swiper slider for the banners.
The banners will be fetched from APIs. How do I append slides to the swiper once it reaches the last slide. I am using onReachEnd function to trigger the api call. Not sure how to append slides dynamically.
export const HeroSlider = () => {
const [pageNumber, setCurrentPageNumber ] = useState(0)
const { homeBannerData, isLoading, error } = useBannerData(pageNumber)
var dataHomeBanner = []
if (homeBannerData && homeBannerData.result) {
dataHomeBanner = dataHomeBanner.concat(homeBannerData.result.data)
}
function fetchBannerData() {
setCurrentPageNumber(pageNumber+1)
if (homeBannerData && homeBannerData.result) {
dataHomeBanner = dataHomeBanner.concat(homeBannerData.result.data)
}
}
return (
/* Hero Banner Start */
<section className="hero-slider">
<Swiper
slidesPerView={1}
watchSlidesVisibility = {true}
navigation
onReachEnd={() => fetchBannerData()}
autoHeight = {true}
>
{dataHomeBanner && dataHomeBanner.map((slide, index)=>{
return (
<SwiperSlide key={index}>
<img src={slide.image alt={slide.title} className="w-100"/>
<Container>
<div className="hero-slider-body d-flex align-items-end align-items-md-center">
<Row>
<Col md={12}>
<div className="hero-slider-caption">
<h1>{slide.title}</h1>
<p>{slide.description}</p>
</div>
</Col>
</Row>
</div>
</Container>
</SwiperSlide>
)
})}
</Swiper>
</section>
/* Hero Banner End */
)
}
useBannerData is returning the banner data.
Right now this code is adding the new slides and replacing the old ones once it fetches data with a new page number. I want it to append at the end of the last slides so that when a user reaches the last slide and clicks on next slide it should fetch data and append it at the end of last slide.
TIA!

Render react component, based from other file option

I have a templates.js file where i set values manually:
export const galleries = [{name:'default'},{name:'carousel'},{name:'grid',set:true}];
If object contain {set:true} I want to render a specific component on product.js page.
I was thinking at:
const gallery = galleries.find(gallery=>gallery.set==true).name
then render:
<div>
gallery == "grid" ? (
<Grid />
) : gallery == "carousel" ? (
<Carousel />
) : (
<Default />
)
</div>
But it's a little messy...
Is there a better aproach or is there already a package that did this?
const Component = {
grid: <Grid />,
carousel: <Carousel />,
default: <Default />
}
Option 1:
render:
<div>
{Component[gallery]}
</div>
Option 2:
I recommend you to validate gallery because the find function may returns null:
const item = galleries.find(gallery=>gallery.set==true);
const gallery = item ? item.name : "default";
then:
<div>
{Component[gallery]}
</div>

Unable to load images dynamically in react app

I have this component :-
const CollectionItem = ({ item }) => (
<div className='collection-item'>
<div
className='image'
style={{
backgroundImage: `url(${item.imageUrl})`
}} />
</div>
</div>
)
my images urls are like ../../assets/images/imageName.jpg
i have tried loading a an image in the css file associated with this component with this exact url. It is working with css, but not in jsx. Please help.
Generally, how you load images in react is to import the image from the specified folder (webpack converts it into the correct source behind the scenes), and then to use that imported variable as the src of the image.
import imgSource from "../../assets/images/imageName.jpg";
const CollectionItem = ({ item }) => (
<div className='collection-item'>
<div
className='image'
style={{
backgroundImage: `url(${imgSource})`
}} />
</div>
</div>
)
EDIT
In the cases where the import depends upon the props, you could simple dynamically import the image within the function itself:
const CollectionItem = ({ item }) => (
import imgSource from `${item.imageUrl}`;
<div className='collection-item'>
<div
className='image'
style={{
backgroundImage: `url(${imgSource})`
}} />
</div>
</div>
)
In the case that it does not work, you can try using require instead
const imgSource = require(item.imageUrl);

React: Loading image based on dynamic path results in error

I'm trying to load images based on a dynamic path in react but the result is the following error Cannot find module <path>
The following code is working
const TestImage = () => {
return (
<div className="image-wrapper">
<img src={require('./../../../assets/images/guy-holding-pencil.jpg')} />
</div>
);
};
I broke down the dynamic part to the use of a variable which is not working
const TestImage = () => {
const image = './../../../assets/images/guy-holding-pencil.jpg';
return (
<div className="image-wrapper">
<img src={require(`${image}`)} />
</div>
);
};
The path is correct. The only difference is the variable. The result:
Error: Cannot find module './../../../assets/images/guy-holding-pencil.jpg'.
Edit: My project is created with create-react-app
How about this approach ?
import IMAGE1 from './../../../assets/images/guy-holding-pencil.jpg';
Then
const TestImage = () => {
return (
<div className="image-wrapper">
<img src={IMAGE1} />
</div>
);
};
In some case you can use command require, because exists deffer between relative and absolute path.
I try go to npmj org and find dropzone plugin for solving this problem

Resources