Created
February 9, 2017 14:40
-
-
Save diegocasmo/db0f5c5064ef9bd744cac5c41d9b43e7 to your computer and use it in GitHub Desktop.
Implementation of a <Tabs/> component in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source code for full implementation (including tests) can be found here: https://gist.github.com/diegocasmo/5cd978e9c5695aefca0c6a8a19fa4c69