Solution

To use goTo of ant design carousel in react js, first install ant design library using npm install antd command import carousel component from it. You have to use the ref={carouselRef} component.

Snippet

In this snippet, see a short example for using the carousel component of the ant design library to set the background color and height from inline css, with the use of the <div> element and the <h3> element. style={{use background-color: 'yellow' , height: 400}}. The handleclick function is called when the button is clicked. This method is called goto method.

<Carousel ref={carouselRef}>
        <div ><h3 style={{
          backgroundColor: 'yellow',
          height: 400
        }}>Item 1</h3></div>
        <div><h3 style={{
          backgroundColor: 'blue',
          height: 400
        }}>Item 2</h3></div>
        <div><h3 style={{
          backgroundColor: 'green',
          height: 400
        }}>Item 3</h3></div>
</Carousel>
  <button style={{ backgroundColor: 'red' }} onClick={handleClick}>Go to slide 3</button>

Example

In this example, we will import the Carousel component from the ant library, The useRef hook is used to create a reference to the carousel.

Let’s start coding…

App.js

import React, { useRef } from 'react';
import { Carousel } from 'antd';

export default function MyCarousel() {
  const carouselRef = useRef();

  const handleClick = () => {
    carouselRef.current.goTo(2); // Go to the third slide (index starts from 0)
  };

  return (
    <>
      <Carousel ref={carouselRef}>
        <div ><h3 style={{
          backgroundColor: 'yellow',
          height: 400
        }}>Item 1</h3></div>
        <div><h3 style={{
          backgroundColor: 'blue',
          height: 400
        }}>Item 2</h3></div>
        <div><h3 style={{
          backgroundColor: 'green',
          height: 400
        }}>Item 3</h3></div>
      </Carousel>
      <button style={{ backgroundColor: 'red' }} onClick={handleClick}>Go to slide 3</button>
    </>
  );
}

Output

Ant-design, goTo, of, ant, design, carousel

Here, we are provided code sandbox links for the above program to use goTo of ant design carousel. Then you can use whenever you went and do the changes as per your requirements

codesandbox

Happy Coding,

I hope the above example with help you to do your task.