Fakultas Ilmu Komputer UI

Tabs.jsx 1.41 KB
Newer Older
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
import React from 'react';

export default class Tabs extends React.Component {
  static displayName = 'Tabs';

  static propTypes = {
    selected: React.PropTypes.number.isRequired,
    children: React.PropTypes.oneOfType([
      React.PropTypes.array,
      React.PropTypes.element,
    ]).isRequired,
  };

  static defaultProps = () => ({
    selected: 0,
  });

  constructor(props) {
    super(props);
    this.state = {
      selected: this.props.selected,
    };
  }

  shouldComponentUpdate = (nextProps, nextState) => (
      this.props !== nextProps || this.state !== nextState
  );

  handleClick = (index, event) => {
    event.preventDefault();
    this.setState({
      selected: index,
    });
  };

  _renderTitles = () => {
    function labels(child, index) {
      const activeClass = (this.state.selected === index ? 'active' : '');
      return (
        <li key={index}>
41
          <a className={activeClass} href="#" onClick={this.handleClick.bind(this, index)}>
42
            {child.props.label}
43
          </a>
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
        </li>
      );
    }
    return (
      <ul className="tabs__labels">
        {this.props.children.map(labels.bind(this))}
      </ul>
    );
  };

  _renderContent = () => (
    <div className="tabs__content">
      {this.props.children[this.state.selected]}
    </div>
    );


  render = () => (
    <div className="tabs">
      {this._renderTitles()}
      {this._renderContent()}
    </div>
    );
}