aboutsummaryrefslogtreecommitdiffstats
path: root/ui/app/components/button-group/button-group.component.js
blob: 17a281030bd71e5c207c012b3906e7bb32f539b5 (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
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'

export default class ButtonGroup extends PureComponent {
  static propTypes = {
    defaultActiveButtonIndex: PropTypes.number,
    noButtonActiveByDefault: PropTypes.bool,
    disabled: PropTypes.bool,
    children: PropTypes.array,
    className: PropTypes.string,
    style: PropTypes.object,
    newActiveButtonIndex: PropTypes.number,
  }

  static defaultProps = {
    className: 'button-group',
    defaultActiveButtonIndex: 0,
  }

  state = {
    activeButtonIndex: this.props.noButtonActiveByDefault
      ? null
      : this.props.defaultActiveButtonIndex,
  }

  componentDidUpdate (_, prevState) {
    // Provides an API for dynamically updating the activeButtonIndex
    if (typeof this.props.newActiveButtonIndex === 'number' && prevState.activeButtonIndex !== this.props.newActiveButtonIndex) {
      this.setState({ activeButtonIndex: this.props.newActiveButtonIndex })
    }
  }

  handleButtonClick (activeButtonIndex) {
    this.setState({ activeButtonIndex })
  }

  renderButtons () {
    const { children, disabled } = this.props

    return React.Children.map(children, (child, index) => {
      return child && (
        <button
          className={classnames(
            'button-group__button',
            { 'button-group__button--active': index === this.state.activeButtonIndex },
          )}
          onClick={() => {
            this.handleButtonClick(index)
            child.props.onClick && child.props.onClick()
          }}
          disabled={disabled || child.props.disabled}
          key={index}
        >
          { child.props.children }
        </button>
      )
    })
  }

  render () {
    const { className, style } = this.props

    return (
      <div
        className={className}
        style={style}
      >
        { this.renderButtons() }
      </div>
    )
  }
}