Skip to content

Instantly share code, notes, and snippets.

@hmtri1011
Last active March 31, 2018 02:33
Show Gist options
  • Save hmtri1011/6c4070ff9d27bf450e589d4bc4a58c0e to your computer and use it in GitHub Desktop.
Save hmtri1011/6c4070ff9d27bf450e589d4bc4a58c0e to your computer and use it in GitHub Desktop.
Dynamic Tab Component
.tab2-header-item {
display: inline-block;
margin-right: 5px;
}
.tab2-header-item.selected {
background: yellow;
}
import React, { Component } from 'react'
import './Tab2.css'
class Tab extends Component {
state = {
activeIndex: parseInt(this.props.defaultActiveIndex) || 0
}
_onChangeTab = index => {
this.setState(({ activeIndex }) => ({ activeIndex: index }))
}
_renderTabHeader = props => (
<TabHeader
{...props}
activeIndex={this.state.activeIndex}
onChangeTab={this._onChangeTab}
/>
)
_renderTabBody = props => (
<TabBody {...props} activeIndex={this.state.activeIndex} />
)
_renderContent = () => {
return React.Children.map(this.props.children, (child, index) => {
if (child.type.name === 'TabHeader')
return this._renderTabHeader(child.props)
if (child.type.name === 'TabBody') return this._renderTabBody(child.props)
})
}
render() {
return <div className="tab2">{this._renderContent()}</div>
}
}
class TabHeader extends Component {
_renderTabHeaderItem = () => {
const { activeIndex } = this.props
return React.Children.map(this.props.children, (child, index) => {
const isSelected = index === activeIndex ? true : false
return (
<TabHeaderItem
{...child.props}
selected={isSelected}
onChangeTab={() => this.props.onChangeTab(index)}
/>
)
})
}
render() {
return <div className="tab2-header">{this._renderTabHeaderItem()}</div>
}
}
class TabHeaderItem extends Component {
render() {
return (
<div
className={`tab2-header-item ${this.props.selected ? 'selected' : ''}`}
onClick={this.props.onChangeTab}
>
{this.props.children}
</div>
)
}
}
class TabBody extends Component {
render() {
const { activeIndex } = this.props
return React.Children.map(this.props.children, (child, index) => {
const selected = activeIndex === index ? true : false
if (selected) return <TabItem {...child.props} />
})
}
}
class TabItem extends Component {
render() {
return <div className="tab2-content-item">{this.props.children}</div>
}
}
export default class TabList extends Component {
render() {
return (
<Tab defaultActiveIndex={1}>
<TabHeader>
<TabHeaderItem>
<button>Header 1</button>
</TabHeaderItem>
<TabHeaderItem>
<button>Header 2</button>
</TabHeaderItem>
<TabHeaderItem>
<button>Header 3</button>
</TabHeaderItem>
</TabHeader>
<TabBody>
<TabItem>content 1</TabItem>
<TabItem>content 2</TabItem>
<TabItem>content 3</TabItem>
</TabBody>
</Tab>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment