How to create a Carousel using reactstrap and getting data from props?
I'm new to ReactJS, and I'm trying to create a Carousel inside my project, using Reactstrap. I copied the code from the documentation, and made my customizations as below:
class Example extends Component {
constructor(props) {
super(props);
this.state = {
activeIndex: 0
};
this.next = this.next.bind(this);
this.previous = this.previous.bind(this);
this.goToIndex = this.goToIndex.bind(this);
this.onExiting = this.onExiting.bind(this);
this.onExited = this.onExited.bind(this);
}
onExiting() {
this.animating = true;
}
onExited() {
this.animating = false;
}
next() {
if (this.animating) return
const nextIndex = this.state.activeIndex === this.items.length - 1 ? 0 : this.state.activeIndex + 1;
this.setState({ activeIndex: nextIndex });
}
previous() {
if (this.animating) return
const nextIndex = this.state.activeIndex === 0 ? this.items.length - 1 : this.state.activeIndex - 1;
this.setState({ activeIndex: nextIndex });
}
goToIndex(newIndex) {
if (this.animating) return;
this.setState({ activeIndex: newIndex });
}
render() {
const { activeIndex } = this.state;
const items = this.props.items
const slides = items.map((item) => {
return (
<CarouselItem
onExiting={this.onExiting}
onExited={this.onExited}
key={item.id}
>
<img src={item.img} alt={item.title}/>
<CarouselCaption captionText={item.title} captionHeader={item.title} />
</CarouselItem>
);
});
return (
<Carousel
activeIndex={activeIndex}
next={this.next}
previous={this.previous}
>
<CarouselIndicators items={items} activeIndex={activeIndex} onClickHandler={this.goToIndex} />
{slides}
<CarouselControl direction="prev" directionText="Previous" onClickHandler={this.previous} />
<CarouselControl direction="next" directionText="Next" onClickHandler={this.next} />
</Carousel>
);
}
}
export default Example;
I'm passing to the component the list of items as props and getting it inside the render(). As my value comes from an async, the component renders twice: once with props null and again after receiving the props values, thus updating {const items} and {const slides} values.
But inside the functions previous and next, the value of {this.items} is always undefined. How can I make these functions see the {items} after it got the values?