@bigfishtv/cockpit
Version:
55 lines (47 loc) • 1.37 kB
JavaScript
import React, { Component, Children } from 'react'
import classnames from 'classnames'
import PropTypes from 'prop-types'
export default class Tabs extends Component {
static propTypes = {
onChange: PropTypes.func,
disabled: PropTypes.bool,
className: PropTypes.string,
}
state = { selected: 0 }
componentWillMount() {
this.updateChildren(this.props)
}
componentWillReceiveProps(nextProps) {
this.updateChildren(nextProps)
}
updateChildren(props) {
const children = Children.toArray(props.children).filter(_ => _)
let selected = children.findIndex(child => child.props.selected)
this.setState({ children, selected: selected !== -1 ? selected : this.state.selected })
}
handleClick(tabIndex) {
this.setState({ selected: tabIndex })
this.props.onChange && this.props.onChange(tabIndex)
}
render() {
const { children, selected } = this.state
return (
<div className={classnames('tabs-container', this.props.className)}>
<ul className="tabs">
{children.map((child, i) => (
<li
key={i}
className={classnames('tab', child.props.className, {
['selected']: selected === i,
['disabled']: child.props.disabled || this.props.disabled,
})}
onClick={() => this.handleClick(i)}>
{child.props.title}
</li>
))}
</ul>
{children[selected]}
</div>
)
}
}