I created function to swipe selected product image inside slide with left and right arrow btns. but when clicked it is swiping every item image not single one. i could not use newSlideArray variable outside of the function. can anyone explain me how to swipe single item image in slide ?
Here is my source code:
class ViewCart extends Component { constructor(props){ super(props); this.state = { index: 0 } nextSlide =(item)=> { let newSlideArray = []; item.gallery.map(img => newSlideArray.push(img)) if(this.state.index === (newSlideArray.length - 1)){ this.setState({ index: 0 }) }else{ this.setState({ index: this.state.index + 1 }) } } render() { return ( {this.props.cart.map((item, index) => ( <div> <div className={styles.slide}> <div className={styles.leftArrow} onClick={()=> {this.previousSlide(item)}}>← <div className={styles.rightArrow} onClick={()=> {this.nextSlide(item)}}>→ <img src={item.gallery[this.state.index]} alt="" /> </div> </div> ))} </div> ); } }
[![enter image description here][1]][1]
here is. When right arrow pressed it is swiping every product image to the right not single one. [1]: https://i.stack.imgur.com/Xw0ME.png
Advertisement
Answer
You have to keep the picture index for each item
. I’m using functional style for simplicity.
const [indexes, setIndexes] = useState({});
Asuming the item has an id
:
const nextSlide = (item) => { const curIndex = indexes[item.id] || 0; const newIndex = curIndex === item.gallery.length - 1 ? 0 : curIndex + 1; setIndexes({ ...indexes, [item.id]: newIndex }); };
And then:
<img src={item.gallery[indexes[item.id] || 0]} alt="" />