Images in the folder "images" aren't displayed in the view... the path is correct, browser don't display any error, can somebody help me please?
function Abstract() {
let images = [...document.querySelectorAll('.img')];
images.forEach((img, idx) => {
img.style.backgroundImage = `url(../images/${idx+1}.jpeg)`
})
return (
<div className="slider">
<div className="slider-inner">
<div className="item">
<div className="img">
</div>
</div>
<div className="item">
<div className="img">
</div>
</div>
<div className="item">
<div className="img">
</div>
</div>
</div>
</div>
)
}
Because of the way React works it's generally bad practice (there are exceptions, depending on your cause) to use native DOM methods to check and update the elements. It will tangle with the way that React manages state/DOM updates, and the result is a non-functioning component as you've found out.
Ideally you need an array of image names that you can map over to produce the JSX your component returns.
This is a working example based on your code but I've done four modifications.
I've created an array of image names.
I've created a parent component for Abstract, and passed the array from the parent into Abstract as a prop. (Note: this wasn't completely necessary, you could have declared the array in Abstract but this seemed more appropriate).
In Abstract I map over the array to create an img for each element with a specific class based on its name (image image1 etc).
I use CSS to define the background image information (I've used dummy images here).
const { useState } = React;
// Pass in the images array as a prop
// `map` over the array to create some images
// adding a new `className` to the image using the image name
function Abstract({ images }) {
return (
<div>
{images.map(src => {
const cn = `image ${src}`;
return <img className={cn} />
})}
</div>
);
}
const images = ['image1', 'image2', 'image3'];
// Pass in the images array as a prop to `Abstract`
function Example({ images }) {
return <Abstract images={images} />
}
ReactDOM.render(
<Example images={images} />,
document.getElementById('react')
);
.image { width: 100px; height: 100px; }
.image1 { background-image: url('https://dummyimage.com/100x100/666/ff0'); }
.image2 { background-image: url('https://dummyimage.com/100x100/999/ff0'); }
.image3 { background-image: url('https://dummyimage.com/100x100/222/ff0'); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Maybe try :
let idx=1
return (
<div class="slider">
<div class="slider-inner">
<div class="item">
<div class="img" style="background-image: `url(../images/${idx++}.jpeg)`">
</div>
</div>
// repeat 3 times
</div>
</div>
)