@hbsis.uikit/react
Version:
Biblioteca ReactJS
143 lines (124 loc) • 3.62 kB
JavaScript
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import cx from 'classnames'
import ButtonGroupStyled from './button-group.styled'
class ButtonGroup extends Component {
constructor(props) {
super(props)
this.state = {
value: props.value ? [props.value] : []
}
switch (props.behavior) {
case 'check':
this.state = {
...this.state,
value: props.value ? [...props.value] : []
}
break;
case 'radio':
this.state = {
...this.state,
value: props.value
}
break;
}
}
activateButton = (value) => {
const { onChange, behavior, clearableOnRadio } = this.props
if (behavior === 'normal')
return
let newValue
if (behavior === 'check') {
if (!this.isButtonActive(value))
newValue = [...this.state.value, value]
else
newValue = this.state.value.filter(e => e !== value)
} else if (behavior === 'radio') {
if (clearableOnRadio && this.state.value === value)
newValue = undefined
else
newValue = value
}
this.setState({value: newValue})
if (onChange)
onChange(newValue)
}
isButtonActive = (value) => {
const { behavior } = this.props
if (behavior === 'normal')
return
if (behavior === 'check')
return (this.state.value.indexOf(value) > -1)
else
return (this.state.value === value)
}
render() {
const {
className,
type,
behavior,
width,
orientation,
children,
outline,
clearableOnRadio
} = this.props
const {} = this.state
let _children = []
let newProps
if (type)
newProps = { type: type }
children.map((component, i) => {
const btn = React.cloneElement(component, { ...newProps, _onClick: component.props.onClick, onClick: () => {
const triggerOnClick = (behavior === 'normal' || !this.isButtonActive(component.props.value || i))
this.activateButton(component.props.value || i)
if (btn.props._onClick && triggerOnClick)
btn.props._onClick()
}, key: i, className: this.isButtonActive(component.props.value || i) ? 'active' : '',
icon: (component.props.icon != undefined ? React.cloneElement(component.props.icon, {active: this.isButtonActive(component.props.value || i)}) : undefined) })
_children.push(btn)
})
return (
<ButtonGroupStyled
className={cx({
'button-group-outline': outline,
'button-group-horizontal': (orientation === 'horizontal'),
'button-group-vertical': (orientation === 'vertical')
}, className, type)}
width={width}
orientation={orientation}>
{_children}
</ButtonGroupStyled>
)
}
}
ButtonGroup.propTypes = {
className: PropTypes.string,
type: PropTypes.oneOf([
'primary',
'secondary',
'danger',
'default',
null
]),
behavior: PropTypes.oneOf([
'normal',
'radio',
'check'
]),
clearableOnRadio: PropTypes.bool,
outline: PropTypes.bool,
width: PropTypes.string,
orientation: PropTypes.string,
children: PropTypes.oneOfType([PropTypes.element, PropTypes.array]),
onChange: PropTypes.func
}
ButtonGroup.defaultProps = {
outline: false,
type: null,
behavior: 'normal',
clearableOnRadio: false,
width: '100%',
orientation: 'horizontal'
}
export { ButtonGroup }