I have been battling this issue. I was able to do this using Javascript but couldn't implement it on React. This is the challenge.
In JS, I used this code:
images.forEach((img, idx) => {
img.style.backgroundImage = `url(./images/${idx + 1}.jpg)`;
});
--to iterate over the folder 'images' and display all images in sequence. The idea was to scroll the images horizontally (full JS code below at the end of this description). I have tried to do the same thing on React js but couldn't figure a way out. I'd tried the same code on JSX but didn't work. I needed a single line of code just as JS to iterate and display all images in React js. I would gladly appreciate your solution.
This is the full JS code:
var images = [...document.querySelectorAll(".img")];
var slider = document.querySelector(".slider");
var sliderWidth;
var imageWidth;
var current = 0;
var target = 0;
var ease = 0.05;
images.forEach((img, idx) => {
img.style.backgroundImage = `url(./images/${idx + 1}.jpg)`;
});
function lerp(start, end, t) {
return start * (1 - t) + end * t;
}
function setTransform(el, transform) {
el.style.transform = transform;
}
function init() {
sliderWidth = slider.getBoundingClientRect().width;
imageWidth = sliderWidth / images.length;
document.body.style.height = `${
sliderWidth - (window.innerWidth - window.innerHeight)
}px`;
}
window.addEventListener("resize", init);
function animate() {
current = parseFloat(lerp(current, target, ease)).toFixed(2);
target = window.scrollY;
setTransform(slider, `translateX(-${current}px)`);
animateImages();
requestAnimationFrame(animate);
}
function animateImages() {
var ratio = current / imageWidth;
var intersectionRatioValue;
images.forEach((image, idx) => {
intersectionRatioValue = ratio - idx * 0.7;
setTransform(image, `translateX(${intersectionRatioValue * 70}px)`);
});
}
init();
animate();
How can I loop over the image folder and display all images using React js?
Without getting into too much of your code, I think what you are looking for is the map function and a structure something like this:
const Images = ({images}) => {
const imageComponents = images.map((img, i) => {
return (
<div key={i}>
<img src={img} alt=`Image number ${i}` />
</div>
)
});
return(
<div>
{images}
<div>
)
}
Basically use the map function on your array and return a component from each iteration (remember to include a unique key prop) and then return that array of components as part of your parent component (in my example, Images. You should be able to pop a lot of your js code into the same component or a parent of Images, depending on the functionality.