slider.jsx
As you can see my code is working fine but in if else there is manually set up like slideIndex if it is less than 2 so i want to make it dynamically change so i don't need to write number if have more data object in my data.js
const Slider = () => {
const [slideIndex, setSlideIndex] = useState(0)
const handleClick=(direction)=>{
if(direction === "left"){
setSlideIndex(slideIndex > 0 ? slideIndex-1:2)
} else {
setSlideIndex(slideIndex < 2 ? slideIndex 1: 0)
}
};
data.js this is my data.js file
here in my data.js there is only 3 object but if i add more objects i have set manually in slider.jsx like if i have 5 object so i have to change manually 2 to 4 how i can do this manually
export const sliderItems = [
{
id: 1,
img: "https://i.ibb.co/DG69bQ4/2.png",
title: "SUMMER SALE",
desc: "DON'T COMPROMISE ON STYLE! GET FLAT 30% OFF FOR NEW ARRIVALS.",
bg: "f5fafd",
},
{
id: 2,
img: "https://i.ibb.co/DG69bQ4/2.png",
title: "AUTUMN COLLECTION",
desc: "DON'T COMPROMISE ON STYLE! GET FLAT 30% OFF FOR NEW ARRIVALS.",
bg: "fcf1ed",
},
{
id: 3,
img: "https://i.ibb.co/cXFnLLV/3.png",
title: "LOUNGEWEAR LOVE",
desc: "DON'T COMPROMISE ON STYLE! GET FLAT 30% OFF FOR NEW ARRIVALS.",
bg: "fbf0f4",
},
];
CodePudding user response:
You should try this one-
const Slider = () => {
const [slideIndex, setSlideIndex] = useState(0)
const handleClick=(direction)=>{
if(direction === "left"){
setSlideIndex(slideIndex==0 ? sliderItems.length-1:slideIndex-1)
} else {
setSlideIndex(slideIndex=== sliderItems.length-1 ? 0: slideIndex 1)
}
};
CodePudding user response:
If understood correctly, I think you can simply use the length property of the array:
const Slider = () => {
const [slideIndex, setSlideIndex] = useState(0)
const handleClick=(direction)=>{
if(direction === "left"){
setSlideIndex(slideIndex > 0 ? slideIndex-1:sliderItems.length)
} else {
setSlideIndex(slideIndex < sliderItems.length ? slideIndex 1: 0)
}
};
CodePudding user response:
Since 2 is that last index of your data that means it is just equal to sliderItems.length - 1
Wherever in the code you need to check for the last index just write sliderItems.length - 1.
This code will be modified as :
const Slider = () => {
const [slideIndex, setSlideIndex] = useState(0)
const handleClick=(direction)=>{
if(direction === "left"){
setSlideIndex(slideIndex > 0 ? slideIndex-1:sliderItems.length)
} else {
setSlideIndex(slideIndex < sliderItems.length ? slideIndex 1: 0)
}
};
