Let's assume that we want to display 5 types of tees:
jsxlet tees = [ { color: 'Pink', pic: 'UrlPink' }, { color: 'Red', pic: 'UrlRed' }, { color: 'Green', pic: 'UrlGreen' }, { color: 'Yellow', pic: 'UrlYellow' }, { color: 'Blue', pic: 'UrlBlue' } } ];
If we want to display an infinite carousel of 3 out of 5 tees:
jsximport React, { useState } from 'react'; const TeeSelector = ({ tees }) => { const [carousel, setCarousel] = useState(tees); const handleNext = () => { let newCarousel = [carousel[1], carousel[2], carousel[3], carousel[4], carousel[0]]; setCarousel(newCarousel); } const handlePrev = () => { let newCarousel = [carousel[4], carousel[0], carousel[1], carousel[2], carousel[3]]; setCarousel(newCarousel); } return( <div className = 'TeeSelector'> <button className = 'Prev' onClick = {handlePrev}>Previous</button> {carousel.slice(0, 3).map( (tee, index) => ( <div className = 'Tee' key = {index}> <img src = {tee.pic}/> </div> ))} <button className = 'Next' onClick = {handleNext}>Next</button> </div> ); } export default TeeSelector;
Every time that we click on button.Next
, the first element will place itself in the last position. If we click on button.Prev
, the last element will place itself in the first position.
You can see a live example at CodePen.
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.