aboutsummaryrefslogtreecommitdiff
path: root/src/settings/components/ui/Input.tsx
blob: 6819ddb540261e3cb81da127c87b0871978da6fc (plain) (blame)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import React from "react";
import "./Input.scss";

interface Props extends React.AllHTMLAttributes<HTMLElement> {
  name: string;
  type: string;
  error?: string;
  label: string;
  value: string;
  onValueChange?: (name: string, value: string) => void;
  onBlur?: (e: React.FocusEvent<Element>) => void;
}

class Input extends React.Component<Props> {
  renderText(props: Props) {
    const inputClassName = props.error ? "input-error" : "";
    const pp = { ...props };
    delete pp.onValueChange;
    return (
      <div className="settings-ui-input">
        <label htmlFor={props.id}>{props.label}</label>
        <input
          type="text"
          className={inputClassName}
          onChange={this.bindOnChange.bind(this)}
          {...pp}
        />
      </div>
    );
  }

  renderRadio(props: Props) {
    const inputClassName = props.error ? "input-error" : "";
    const pp = { ...props };
    delete pp.onValueChange;
    return (
      <div className="settings-ui-input">
        <label>
          <input
            type="radio"
            className={inputClassName}
            onChange={this.bindOnChange.bind(this)}
            {...pp}
          />
          {props.label}
        </label>
      </div>
    );
  }

  renderTextArea(props: Props) {
    const inputClassName = props.error ? "input-error" : "";
    const pp = { ...props };
    delete pp.onValueChange;
    return (
      <div className="settings-ui-input">
        <label htmlFor={props.id}>{props.label}</label>
        <textarea
          className={inputClassName}
          onChange={this.bindOnChange.bind(this)}
          {...pp}
        />
        <p className="settings-ui-input-error">{this.props.error}</p>
      </div>
    );
  }

  render() {
    const { type } = this.props;

    switch (this.props.type) {
      case "text":
        return this.renderText(this.props);
      case "radio":
        return this.renderRadio(this.props);
      case "textarea":
        return this.renderTextArea(this.props);
      default:
        console.warn(`Unsupported input type ${type}`);
    }
    return null;
  }

  bindOnChange(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) {
    if (this.props.onValueChange) {
      this.props.onValueChange(e.target.name, e.target.value);
    }
  }
}

export default Input;