I'm struggling with slider transition in React and styled components.
So slider itself is working but there's no transition between slides, just like another frame in a movie.
There's a slider itself:
const Slider = () => {
const [slideIndex, setSlideIndex] = useState(0)
const handleClick = (e, direction) => {
e.preventDefault();
console.log(slideIndex);
if (direction === "left") {
setSlideIndex(slideIndex > 0 ? slideIndex - 1 : sliderItems.length - 1);
} else {
setSlideIndex(slideIndex < sliderItems.length - 1 ? slideIndex 1 : 0);
}}
return (
<Container>
<Arrow direction="left" onClick={(e)=>handleClick(e,"left")}>
<ArrowLeftSharp />
</Arrow>
<Wrapper>
<Slide key={sliderItems[slideIndex].id}>
<ImgContainer>
<Image src={sliderItems[slideIndex].img} />
</ImgContainer>
<InfoContainer>
<Title>{sliderItems[slideIndex].title}</Title>
<Description>{sliderItems[slideIndex].description}</Description>
<Button>{sliderItems[slideIndex].buttonText}</Button>
</InfoContainer>
</Slide>
</Wrapper>
<Arrow direction="right" onClick={(e)=>handleClick(e,"right")}>
<ArrowRightSharp />
</Arrow>
</Container>
)
}
and here's wrapper styled component:
const Wrapper = styled.div`
height: 100%;
display: flex;
transition: all 0.5s ease;
transform: translateX(${props=> props.slideIndex * -100}vw);
`;
Does anyone has any idea why the transition not working? Thanks in advance
CodePudding user response:
You are not passing the slideIndex
prop to the Wrapper
component, try this:
const Slider = () => {
const [slideIndex, setSlideIndex] = useState(0)
const handleClick = (e, direction) => {
e.preventDefault();
console.log(slideIndex);
if (direction === "left") {
setSlideIndex(slideIndex > 0 ? slideIndex - 1 : sliderItems.length - 1);
} else {
setSlideIndex(slideIndex < sliderItems.length - 1 ? slideIndex 1 : 0);
}}
return (
<Container>
<Arrow direction="left" onClick={(e)=>handleClick(e,"left")}>
<ArrowLeftSharp />
</Arrow>
<Wrapper slideIndex={slideIndex}>
<Slide key={sliderItems[slideIndex].id}>
<ImgContainer>
<Image src={sliderItems[slideIndex].img} />
</ImgContainer>
<InfoContainer>
<Title>{sliderItems[slideIndex].title}</Title>
<Description>{sliderItems[slideIndex].description}</Description>
<Button>{sliderItems[slideIndex].buttonText}</Button>
</InfoContainer>
</Slide>
</Wrapper>
<Arrow direction="right" onClick={(e)=>handleClick(e,"right")}>
<ArrowRightSharp />
</Arrow>
</Container>
)
}
CodePudding user response:
- You don't pass any props to Wrapper component
- You have only one slide not multiple slides