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> ); }
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> ); }
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.
Answer
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> );