aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/ui/Tabs/Tabs.tsx
blob: a5ec148aa6801fbc13937bdc4d96f6a49f674f20 (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
import classnames from 'classnames';
import { observer } from 'mobx-react';
import {
  Children,
  Component,
  type ReactElement,
  type ReactPortal,
} from 'react';
import type { IProps as TabItemProps } from './TabItem';

interface IProps {
  children:
    | ReactElement<TabItemProps>
    | (boolean | ReactElement<TabItemProps>)[];
  active?: number;
}

interface IState {
  active: number;
}

@observer
class Tab extends Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);

    this.state = {
      active: this.props.active || 0,
    };
  }

  switchTab(index: number): void {
    this.setState({ active: index });
  }

  render(): ReactElement {
    const { children: childElements } = this.props;
    const children = Children.toArray(childElements); // removes all null values

    if (children.length === 1) {
      return <div>{children}</div>;
    }

    return (
      <div className="content-tabs">
        <div className="content-tabs__tabs">
          {Children.map(children, (child, i) => (
            <button
              // eslint-disable-next-line react/no-array-index-key
              key={i}
              className={classnames({
                'content-tabs__item': true,
                'is-active': this.state.active === i,
              })}
              onClick={() => this.switchTab(i)}
              type="button"
            >
              {(child as ReactPortal).props.title}
            </button>
          ))}
        </div>
        <div className="content-tabs__content">
          {Children.map(children, (child, i) => (
            <div
              // eslint-disable-next-line react/no-array-index-key
              key={i}
              className={classnames({
                'content-tabs__item': true,
                'is-active': this.state.active === i,
              })}
              // type="button"
            >
              {child}
            </div>
          ))}
        </div>
      </div>
    );
  }
}

export default Tab;