aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/ui/Tabs/Tabs.js
blob: 195398708f0e1836ef7370c8d88ce767d0601221 (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
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import classnames from 'classnames';

import { oneOrManyChildElements } from '../../../prop-types';

@observer
class Tab extends Component {
  constructor(props) {
    super(props);
    this.state = { active: this.props.active };
  }

  static propTypes = {
    children: oneOrManyChildElements.isRequired,
    active: PropTypes.number,
  };

  static defaultProps = {
    active: 0,
  };

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

  render() {
    const { children: childElements } = this.props;
    const children = childElements.filter(c => !!c);

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

    return (
      <div className="content-tabs">
        <div className="content-tabs__tabs">
          {React.Children.map(children, (child, i) => (
            <button
              key="{i}"
              className={classnames({
                'content-tabs__item': true,
                'is-active': this.state.active === i,
              })}
              onClick={() => this.switchTab(i)}
              type="button"
            >
              {child.props.title}
            </button>
          ))}
        </div>
        <div className="content-tabs__content">
          {React.Children.map(children, (child, i) => (
            <div
              key="{i}"
              className={classnames({
                'content-tabs__item': true,
                'is-active': this.state.active === i,
              })}
              type="button"
            >
              {child}
            </div>
          ))}
        </div>
      </div>
    );
  }
}

export default Tab;