Skip to content

Instantly share code, notes, and snippets.

@salmanx
Last active January 15, 2020 03:20
Show Gist options
  • Save salmanx/2797f4b1de4535596029e30b0e71d180 to your computer and use it in GitHub Desktop.
Save salmanx/2797f4b1de4535596029e30b0e71d180 to your computer and use it in GitHub Desktop.
Reusable tab component
import React, { Component } from 'react';
import Tab from '/modules/tab/Tab';
import TabPane from '/modules/tab/TabPane';
export default class Index extends Component {
render() {
return (
<React.Fragment>
<Tab activeTab="1">
<TabPane tab="1">
Tab 1
</TabPane>
<TabPane tab="2">
Tab 2
</TabPane>
<TabPane tab="3">
Tab 3
</TabPane>
</Tab>
</React.Fragment>
);
}
}
import React, { Component } from 'react';
import styled from 'styled-components';
export default class Tab extends Component {
constructor(props) {
super(props);
console.log(this.props);
this.state = {
activeTabIndex: 1
};
}
render() {
const { children } = this.props;
return (
<TabContainer>
<nav>
{children.map((el, i) => (
<div
key={i}
className={this.state.activeTabIndex === parseInt(el.props.tab, 10) ? 'active tab_button' : 'tab_button'}
onClick={() => this.setState({ activeTabIndex: parseInt(el.props.tab, 10) })}
>
Tab {el.props.tab}{' '}
</div>
))}
</nav>
<div>{children[this.state.activeTabIndex - 1]}</div>
</TabContainer>
);
}
}
const TabContainer = styled.div`
nav {
padding: 0px 40px;
.tab_button {
display: inline-block;
font-size: 1em;
font-weight: 100;
border: 0;
padding: 15px;
margin: 0 4px;
background-color: #ffffff;
cursor: pointer;
}
.active {
border-bottom: 2px solid #40b6da;
}
}
`;
import React, { Component } from 'react';
import styled from 'styled-components';
export default class TabPane extends Component {
render() {
return (
<TabPaneContainer>
<div className="tabContent">{this.props.children}</div>
</TabPaneContainer>
);
}
}
const TabPaneContainer = styled.div`
background-color: #f2f4f4;
padding: 30px 40px;
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment