Skip to content

Instantly share code, notes, and snippets.

@diegocasmo
Created February 9, 2017 14:40
Show Gist options
  • Save diegocasmo/db0f5c5064ef9bd744cac5c41d9b43e7 to your computer and use it in GitHub Desktop.
Save diegocasmo/db0f5c5064ef9bd744cac5c41d9b43e7 to your computer and use it in GitHub Desktop.
Implementation of a <Tabs/> component in React
export class Tabs extends Component {
constructor(props, context) {
super(props, context);
this.state = {
activeTabIndex: this.props.defaultActiveTabIndex
};
this.handleTabClick = this.handleTabClick.bind(this);
}
// Toggle currently active tab
handleTabClick(tabIndex) {
this.setState({
activeTabIndex: tabIndex === this.state.activeTabIndex ? this.props.defaultActiveTabIndex : tabIndex
});
}
// Encapsulate <Tabs/> component API as props for <Tab/> children
renderChildrenWithTabsApiAsProps() {
return React.Children.map(this.props.children, (child, index) => {
return React.cloneElement(child, {
onClick : this.handleTabClick,
tabIndex: index,
isActive: index === this.state.activeTabIndex
});
});
}
// Render current active tab content
renderActiveTabContent() {
const {children} = this.props;
const {activeTabIndex} = this.state;
if(children[activeTabIndex]) {
return children[activeTabIndex].props.children;
}
}
render() {
return (
<div className="tabs">
<ul className="tabs-nav nav navbar-nav navbar-left">
{this.renderChildrenWithTabsApiAsProps()}
</ul>
<div className="tabs-active-content">
{this.renderActiveTabContent()}
</div>
</div>
);
}
};
@diegocasmo
Copy link
Author

Source code for full implementation (including tests) can be found here: https://gist.github.com/diegocasmo/5cd978e9c5695aefca0c6a8a19fa4c69

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment