Repository URL to install this package:
|
Version:
8.0.0 ▾
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Wrapper, Tab, TabList, TabPanel } from 'react-aria-tabpanel';
class Tabs extends Component {
static propTypes = {
/** A callback to run when the user changes tabs (i.e. clicks a tab or navigates to another with the arrow keys), receiving a `{ activeTab: String }` object. If provided, the Tabs component is stateless. */
onChange: PropTypes.func,
activeTab: PropTypes.string,
items: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
/** Tab label */
label: PropTypes.node.isRequired,
/** Panel content: can by a `PropType.node` or a `PropType.function` receiving a `{ isActive: Boolean }` object. Panels are re-rendered when tabs change. */
content: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
})
).isRequired,
variant: PropTypes.oneOf(['dark', 'light']),
};
static defaultProps = {
onChange: null,
variant: 'dark',
activeTab: null,
};
constructor(props) {
super(props);
this.state = { activeTab: props.activeTab || (props.items.length > 0 && props.items[0].id) };
}
componentWillReceiveProps(nextProps) {
const { activeTab } = this.state;
if (nextProps.activeTab !== null && nextProps.activeTab !== activeTab) {
this.setState({ activeTab: nextProps.activeTab });
this.wrapper.manager.focusTab(nextProps.activeTab);
}
}
setTab = newActiveTabId => {
this.setState({ activeTab: newActiveTabId });
if (typeof this.props.onChange === 'function') {
this.props.onChange({ activeTab: newActiveTabId });
}
};
render() {
const { items, variant } = this.props;
const { activeTab } = this.state;
const tabs = items.map(({ id, label }) => (
<li className="Tabs-tablistItem" key={`TablistItem-${id}`}>
<Tab id={id} className={`Tabs-tab ${id === activeTab ? 'is-active' : 'is-inactive'}`} active={id === activeTab}>
{label}
</Tab>
</li>
));
const panels = items.map(({ id, content }) => (
<TabPanel key={`Panel-${id}`} tabId={id} active={id === activeTab}>
{content || <div />}
</TabPanel>
));
return (
<Wrapper
className={`Tabs Tabs--${variant}`}
onChange={this.setTab}
activeTabId={activeTab}
letterNavigation
ref={wrapper => {
this.wrapper = wrapper;
}}
>
<TabList>
<ul className="Tabs-tabList">{tabs}</ul>
</TabList>
<div className="Tabs-panels">{panels}</div>
</Wrapper>
);
}
}
export default Tabs;