aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/ui/Radio.tsx
blob: b5be64c5d8b8c3df1f078a3502016bafc54bd3dd (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
import { Component } from 'react';
import { observer } from 'mobx-react';
import { Field } from 'mobx-react-form';
import classnames from 'classnames';

type Props = {
  field: typeof Field;
  className: string;
  focus: boolean;
  showLabel: boolean;
};

// TODO: Should this file be converted into the coding style similar to './toggle/index.tsx'?
class Radio extends Component<Props> {
  static defaultProps = {
    focus: false,
    showLabel: true,
  };

  inputElement = null;

  componentDidMount() {
    if (this.props.focus) {
      this.focus();
    }
  }

  focus() {
    // @ts-expect-error Object is possibly 'null'.
    this.inputElement.focus();
  }

  render() {
    const { field, className, showLabel } = this.props;

    return (
      <div
        className={classnames({
          'franz-form__field': true,
          'has-error': field.error,
          [`${className}`]: className,
        })}
      >
        {field.label && showLabel && (
          <label className="franz-form__label" htmlFor={field.name}>
            {field.label}
          </label>
        )}
        <div className="franz-form__radio-wrapper">
          {field.options.map(type => (
            <label
              key={type.value}
              htmlFor={`${field.id}-${type.value}`}
              className={classnames({
                'franz-form__radio': true,
                'is-selected': field.value === type.value,
              })}
            >
              <input
                id={`${field.id}-${type.value}`}
                type="radio"
                name="type"
                value={type.value}
                onChange={field.onChange}
                checked={field.value === type.value}
              />
              {type.label}
            </label>
          ))}
        </div>
        {field.error && <div className="franz-form__error">{field.error}</div>}
      </div>
    );
  }
}

export default observer(Radio);