Rashomon
Rashomon

Reputation: 6792

How to wrap Carousel.Item in other component

I am working in this react-bootstrap carousel. Current code is working well:

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <Carousel>
        <Carousel.Item>
          <img
            className="d-block w-100"
            src="https://res.cloudinary.com/tpostr/image/upload/v1553865338/paparouna/IMG_7638-01.jpg"
            alt="First slide"
          />
        </Carousel.Item>
        <Carousel.Item>
          <img
            className="d-block w-100"
            src="https://res.cloudinary.com/tpostr/image/upload/v1553865338/paparouna/IMG_7638-01.jpg"
            alt="First slide"
          />
        </Carousel.Item>
      </Carousel>
    </div>
  );
}

Demo working well

Now Im trying to separate Carousel.Item to other component, so I can use it without repeating myself. But the image doesnt appear:

const CarouselItem = () => (
  <Carousel.Item>
    <img
      className="d-block w-100"
      src="https://res.cloudinary.com/tpostr/image/upload/v1553865338/paparouna/IMG_7638-01.jpg"
      alt="First slide"
    />
  </Carousel.Item>
);

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <Carousel>
        <CarouselItem />
        <CarouselItem />
      </Carousel>
    </div>
  );
}

Demo with error

I have tried wrapping the component with forwardRef, but didnt work. What Im doing wrong? Note: I need CarouselItem to be a component/function in order to be able to send props to it.

Upvotes: 2

Views: 776

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282160

When you render the Carousel.Item in a separate component, you need to forward the props to it.

Internally Carousel will be using React.cloneElement to add extra props to the Carousel.Item which when you use a custom component need to forward to Carousel.Item

const CarouselItem = (props) => (
  <Carousel.Item {...props}>
    <img
      className="d-block w-100"
      src="https://res.cloudinary.com/tpostr/image/upload/v1553865338/paparouna/IMG_7638-01.jpg"
      alt="First slide"
    />
  </Carousel.Item>
);

Working demo

Upvotes: 4

Related Questions