All files / javascripts/explorev2/components/controls TextControl.jsx

0% Statements 0/28
0% Branches 0/14
0% Functions 0/3
0% Lines 0/28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75                                                                                                                                                     
import React from 'react';
import PropTypes from 'prop-types';
import { FormGroup, FormControl } from 'react-bootstrap';
import * as v from '../../validators';
 
const propTypes = {
  name: PropTypes.string.isRequired,
  label: PropTypes.string,
  description: PropTypes.string,
  onChange: PropTypes.func,
  value: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
  ]),
  isFloat: PropTypes.bool,
  isInt: PropTypes.bool,
};
 
const defaultProps = {
  label: null,
  description: null,
  onChange: () => {},
  value: '',
  isInt: false,
  isFloat: false,
};
 
export default class TextControl extends React.Component {
  constructor(props) {
    super(props);
    const value = props.value ? props.value.toString() : '';
    this.state = { value };
    this.onChange = this.onChange.bind(this);
  }
  onChange(event) {
    let value = event.target.value || '';
    this.setState({ value });
 
    // Validation & casting
    const errors = [];
    if (this.props.isFloat) {
      const error = v.numeric(value);
      if (error) {
        errors.push(error);
      } else {
        value = parseFloat(value);
      }
    }
    if (this.props.isInt) {
      const error = v.integer(value);
      if (error) {
        errors.push(error);
      } else {
        value = parseInt(value, 10);
      }
    }
    this.props.onChange(value, errors);
  }
  render() {
    return (
      <FormGroup controlId="formInlineName" bsSize="small">
        <FormControl
          type="text"
          placeholder=""
          onChange={this.onChange}
          value={this.state.value}
        />
      </FormGroup>
    );
  }
}
 
TextControl.propTypes = propTypes;
TextControl.defaultProps = defaultProps;