I have a react image gallery that is driven off an array of objects and within each object is an array of image paths. I've created a next function used with an onClick that increments the "imgPos" variable which is the array position. However, after the initial image changes, it stops working for the next clicks. (FYI- I've console logged to confirm that the logic is working fine but the image is not updating...see screen capture below).
Sample Code:
const [imgPos, setImgPos] =useState(0)
export const FeaturedList = [
{id: 0,
street: "5228 Chelsea St",
city: "La Jolla",
beds: 5,
baths: 8,
sqft: 8878,
mainimg: './images/5228main.webp' ,
images: ['./images/5228main.webp','./images/5228(2).webp','./images/52283.webp','./images/5228(4).webp','./images/5228(5).webp','./images/5228(6).webp','./images/5228(7).webp'] ,
price: '$12,995,000' ,
},
...
The function:
const nextimg = () =>{
if((imgPos 1) > (FeaturedList[0].images.length -1)) {
setImgPos(imgPos = 0)
console.log("I'm the new imgPos#" imgPos "The length minus 1 is" "FeaturedList[0].images.length -1")
} else{
setImgPos(imgPos 1);
console.log("There are 7 images for this object. The current imgPos is:" imgPos )
}
Here is where the imgPos variable is utilized:
return(
<div className="ft-disp-sec" style={{backgroundImage:`URL(${FeaturedList[0].images[imgPos]})`,backgroundPosition: 'center',
backgroundSize: 'cover', backgroundRepeat: 'no-repeat', height: "100vh",}}>
<div className="ft-disp-arrows">
<img src={prev} className="ft-disp-prev" onClick={previmg}/>
<img src={next} className="ft-disp-next" onClick={nextimg}/>
</div>
</div>
)
}
Below is the console log. the second line where it states "The current impPos is:1 is the last time the image changes. No matter how many times you click it does not update again. Also, I noticed the console.log for setImgPos(imgPos = 0) never fires regardless of how many times I click the button.
Can you please advise on what is wrong with this code?
CodePudding user response:
I'm no expert in React but I think the way you are setting the state in the setter function is not working as expected.
Try using the state setter like this setImgPos(prevState => prevState = 0)
and setImgPos(prevState => prevState = 1)
CodePudding user response:
Here Is a Codesandbox in which I have a simplified setup for this.
You should never mutate the state variable directly like you do with setImgPos(imgPos = 0)
.
You can either give the value directly like setImgPos(0)
or give a callback function in which you increment or decrement the previous state setImgPos(prevState => prevState 1)
So with this in mind we can take you nextImg function and change it accordingly
const nextimg = () => {
if(imgPos >= FeaturedList[0].images.length - 1) {
setImgPos(0)
} else{
setImgPos(prevState => prevState 1);
}
}