github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/build-blockchain-insurance-app-master/web/src/shared/SelectList.js (about)

     1  'use strict';
     2  
     3  import React, { Props } from 'react';
     4  import PropTypes from 'prop-types';
     5  
     6  class SelectList extends React.Component {
     7  
     8    static get propTypes() {
     9      return {
    10        options: PropTypes.array.isRequired,
    11        getCaptionFunc: PropTypes.func.isRequired,
    12        onChange: PropTypes.func,
    13        selectedItemIndex: PropTypes.number
    14      };
    15    }
    16  
    17    constructor(props) {
    18      super(props);
    19  
    20      const selectedItemIndex = props.selectedItemIndex || 0; // Fallback to the first
    21      this.state = { selectedItemIndex };
    22  
    23      this.optionItem = this.optionItem.bind(this);
    24      this.onChange = this.onChange.bind(this);
    25    }
    26  
    27    componentDidMount() {
    28      let elem = jQuery(this.refs.selectElement);
    29      elem.select2();
    30      elem.on('change', this.onChange);
    31    }
    32  
    33    componentWillUnmount() {
    34      jQuery(this.refs.selectElement).off('change', this.onChange);
    35    }
    36  
    37    onChange() {
    38      const selectedItemIndex = Number(jQuery(this.refs.selectElement).val());
    39      this.setState({ selectedItemIndex });
    40      setTimeout(() => {
    41        if (typeof this.props.onChange === 'function') {
    42          this.props.onChange(this.props.options[selectedItemIndex]);
    43        }
    44      });
    45    }
    46  
    47    optionItem(data, index) {
    48      return (
    49        <option key={index} value={index}>{this.props.getCaptionFunc(data)}</option>
    50      );
    51    }
    52  
    53    render() {
    54      const { options } = this.props;
    55      return (
    56        <select ref='selectElement' readOnly value={this.state.selectedItemIndex}>
    57          {this.props.options.map(this.optionItem)}
    58        </select>
    59      );
    60    }
    61  }
    62  
    63  export default SelectList;
    64  
    65  
    66