2018-07-20 19:25:45 +02:00
|
|
|
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,
|
2018-08-16 14:28:27 +02:00
|
|
|
noButtonActiveByDefault: PropTypes.bool,
|
2018-07-20 19:25:45 +02:00
|
|
|
disabled: PropTypes.bool,
|
|
|
|
children: PropTypes.array,
|
|
|
|
className: PropTypes.string,
|
|
|
|
style: PropTypes.object,
|
2018-09-20 06:16:43 +02:00
|
|
|
newActiveButtonIndex: PropTypes.number,
|
2018-07-20 19:25:45 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
static defaultProps = {
|
|
|
|
className: 'button-group',
|
2018-09-09 18:18:34 +02:00
|
|
|
defaultActiveButtonIndex: 0,
|
2018-07-20 19:25:45 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
state = {
|
2018-08-16 14:28:27 +02:00
|
|
|
activeButtonIndex: this.props.noButtonActiveByDefault
|
|
|
|
? null
|
2018-09-09 18:18:34 +02:00
|
|
|
: this.props.defaultActiveButtonIndex,
|
2018-07-20 19:25:45 +02:00
|
|
|
}
|
|
|
|
|
2018-09-20 06:16:43 +02:00
|
|
|
componentDidUpdate (_, prevState) {
|
|
|
|
// Provides an API for dynamically updating the activeButtonIndex
|
2018-09-13 14:35:17 +02:00
|
|
|
if (typeof this.props.newActiveButtonIndex === 'number' && prevState.activeButtonIndex !== this.props.newActiveButtonIndex) {
|
2018-09-20 06:16:43 +02:00
|
|
|
this.setState({ activeButtonIndex: this.props.newActiveButtonIndex })
|
2018-09-13 14:35:17 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-20 19:25:45 +02:00
|
|
|
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>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|