Skip to content

Instantly share code, notes, and snippets.

@JonathonAshworth
Last active March 7, 2017 22:24
Show Gist options
  • Save JonathonAshworth/3fcc8114318a88fe1bfcf7904054a520 to your computer and use it in GitHub Desktop.
Save JonathonAshworth/3fcc8114318a88fe1bfcf7904054a520 to your computer and use it in GitHub Desktop.
React Tab components (using css modules)
import React, { Component } from 'react';
import TabList from './TabList';
class TabbedContent extends Component {
static propTypes = {
// Labels must have the same length as props.children
labels: React.PropTypes.arrayOf(React.PropTypes.string)
}
constructor(props) {
super(props);
this.state = { selected: 0 };
}
render() {
return (
<div>
<TabList labels={this.props.labels}
selected={this.state.selected}
setSelected={index => this.setState({ selected: index })} />
{this.props.children[this.state.selected]}
</div>
);
}
}
export default TabbedContent;
.tab {
background-color: #fff;
text-align: center;
padding: 10px;
cursor: pointer;
color: #000;
border-color: #000;
}
.activeTab {
composes: tab;
border-bottom-width: 0.3rem;
border-bottom-style: solid;
}
.tab:hover {
background-color: #eee;
}
import React, { Component } from 'react';
import styles from './Tab-styles.scss';
const propTypes = {
text: React.PropTypes.string,
active: React.PropTypes.bool,
// Propagation
className: React.PropTypes.string,
onClick: React.PropTypes.func
};
const Tab = props =>
<div className={`${props.className} ${props.active ? styles.activeTab : styles.tab}`} onClick={props.onClick}>
{props.text}
</div>
Tab.propTypes = propTypes;
export default Tab;
.tabList {
width: 100%;
display: flex;
align-items: stretch;
}
.tab {
flex-basis: 50%;
}
import React, { Component } from 'react';
import styles from './TabList-styles.scss';
import Tab from './Tab';
const propTypes = {
labels: React.PropTypes.arrayOf(React.PropTypes.string),
selected: React.PropTypes.number,
setSelected: React.PropTypes.func
};
const TabList = props =>
<div className={styles.tabList}>
{props.labels.map((label, index) =>
<Tab key={index}
className={styles.tab}
text={label}
active={index === props.selected}
onClick={() => props.setSelected(index)} />
)}
</div>
TabList.propTypes = propTypes;
export default TabList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment