github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/build-blockchain-insurance-app-master/web/src/shop/components/ProductCarousel.js (about) 1 /*eslint react/no-danger: "off"*/ 2 'use strict'; 3 4 import React, { Props } from 'react'; 5 import PropTypes from 'prop-types'; 6 7 class ProductCarousel extends React.Component { 8 9 static get propTypes() { 10 return { 11 products: PropTypes.array.isRequired, 12 selectedProductIndex: PropTypes.number, 13 onSelectedProduct: PropTypes.func 14 }; 15 } 16 17 constructor(props) { 18 super(props); 19 20 let state = { 21 selected: null 22 }; 23 if (typeof props.selectedProductIndex === 'number') { 24 state.selected = props.products[props.selectedProductIndex]; 25 } 26 this.state = state; 27 this.carouselItem = this.carouselItem.bind(this); 28 this.onSlideChanged = this.onSlideChanged.bind(this); 29 } 30 31 componentWillMount() { 32 // Preselecting the first one, if nothing is selected 33 if (!this.state.selected) { 34 let firstProduct = this.props.products[0]; 35 if (firstProduct) { 36 this.onSelectedProduct(firstProduct); 37 } 38 } 39 } 40 41 componentDidMount() { 42 let elem = jQuery(this.refs.carouselElement); 43 elem.carousel({ 44 autoplay: false 45 }); 46 elem.on('afterChange', this.onSlideChanged); 47 } 48 49 componentWillUnmount() { 50 let elem = jQuery(this.refs.carouselElement); 51 elem.off('afterChange', this.onSlideChanged); 52 } 53 54 onSelectedProduct(product) { 55 if (!product) { 56 return; 57 } 58 this.setState({ selected: product }); 59 if (!this.props.onSelectedProduct) { 60 return; 61 } 62 this.props.onSelectedProduct({ 63 index: this.props.products.indexOf(product), 64 brand: product.brand, 65 model: product.model, 66 price: product.price 67 }); 68 } 69 70 onSlideChanged(event) { 71 if (event.type == 'afterChange') { 72 let activeSlide = jQuery(this.refs.carouselElement) 73 .find('.slick-current.slick-active'); 74 let index = Number(activeSlide.attr('data-slick-index')); 75 this.onSelectedProduct(this.props.products[index]); 76 } 77 } 78 79 carouselItem(product, index) { 80 let isActive = this.selected === product; 81 return ( 82 <div key={index} className={`${isActive ? ' is-active' : ''}`}> 83 <p><img src={product.imgSrc} /></p> 84 <p dangerouslySetInnerHTML={{ __html: product.description }} /> 85 </div> 86 ); 87 } 88 89 render() { 90 return ( 91 <div ref='carouselElement'> 92 {this.props.products.map(this.carouselItem)} 93 </div> 94 ); 95 } 96 } 97 98 export default ProductCarousel;