title: How to control react-bootstrap carousel with custom buttons?
body: <p>here i need to control carousel slides with custom buttons i achieved this with the help of this <a href="https://react-bootstrap.github.io/components/carousel/#controlled" rel="nofollow noreferrer">Example</a>.</p>
  <p>This is the code for it..</p>
  <pre><code>import React, { useState } from &quot;react&quot;;
  import { Carousel, Button, Container, Row } from &quot;react-bootstrap&quot;;
  import Cards from &quot;../cards&quot;;
  import &quot;./slider.css&quot;;
  
  const Slider = () =&gt; {
    const [index, setIndex] = useState(0);
  
    const handleSelect = (selectedIndex, e) =&gt; {
      setIndex(selectedIndex);
    };
  
    const onPrevClick = () =&gt; {
      if (index &gt; 0) {
        setIndex(index - 1);
      } else if (index === 0) setIndex(2);
    };
    const onNextClick = () =&gt; {
      if (index === 2) {
        setIndex(0);
      } else if (index === 0 || index &gt; 0) setIndex(index + 1);
    };
  
    return (
      &lt;&gt;
        &lt;div className=&quot;button-container&quot;&gt;
          &lt;Container&gt;
            &lt;Row&gt;
              &lt;Button variant=&quot;primary&quot; onClick={onPrevClick}&gt;
                Previous
              &lt;/Button&gt;
              &lt;Button variant=&quot;primary&quot; onClick={onNextClick}&gt;
                Next
              &lt;/Button&gt;
            &lt;/Row&gt;
          &lt;/Container&gt;
        &lt;/div&gt;
        &lt;Carousel
          activeIndex={index}
          onSelect={handleSelect}
          indicators={false}
          controls={false}
        &gt;
          &lt;Carousel.Item&gt;
            &lt;Cards /&gt;
          &lt;/Carousel.Item&gt;
          &lt;Carousel.Item&gt;
            &lt;Cards /&gt;
          &lt;/Carousel.Item&gt;
          &lt;Carousel.Item&gt;
            &lt;Cards /&gt;
          &lt;/Carousel.Item&gt;
        &lt;/Carousel&gt;
      &lt;/&gt;
    );
  };
  
  export default Slider;
  </code></pre>
  <p>But when the active index is in last item that means in the last carousel slide. When i press the next button, it moves all the way around from last carousel to first carousel, i.e the direction is like 3 -&gt; 2 -&gt; 1.</p>
  <p>I know that something i made terrible logic in the onClick functions. So i am seeking help to suggest me the best way to control carousel slides with custom buttons , your help is much appreciated. Please review my code and tell me any suggestions. Thanks in advance.</p>
  <p>And here is the <a href="https://codesandbox.io/s/new-efs-examples-up5c7?file=/src/components/slider/index.js" rel="nofollow noreferrer">code sandbox link</a></p>