Reputation: 1745
I am trying to make a simple carousel by following this documentation Carousel
Working example
how can I translate above to use functional components/hooks.
I have been trying to bind next() within an onClick Button however I can't seem to get it to work. How can I correctly access the next method and bind it within my button?
<Carousel ref={c => (this.slider = c)} >
<div>
<h3><Button onClick={() => this.carousel.next()}>1</Button></h3>
</div>
<div>
<h3><Button onClick={() => this.carousel.prev()}>2</Button></h3>
</div>
<div>
<h3>3</h3>
</div>
<div>
<h3>4</h3>
</div>
</Carousel>
Upvotes: 4
Views: 979
Reputation: 29277
You can access the next()
api from the <Carousel />
ref
. With function component, you can use useRef
hook, like this:
import React, { useRef } from "react";
import { Carousel } from "antd";
export function App() {
const carousel = useRef(null);
function next() {
carousel.current.next();
}
return (
<div>
<Carousel ref={carousel}>
<div>
<h3>1</h3>
</div>
<div>
<h3>2</h3>
</div>
<div>
<h3>3</h3>
</div>
<div>
<h3>4</h3>
</div>
</Carousel>
<button onClick={next}>Next</button>
</div>
);
}
https://codesandbox.io/s/carousel-react-ref-hook-next-492gv
Upvotes: 4