Skip to content

Instantly share code, notes, and snippets.

@markus-willems
Created September 27, 2017 13:03
Show Gist options
  • Save markus-willems/11f101c8249041ff92582c2af8818440 to your computer and use it in GitHub Desktop.
Save markus-willems/11f101c8249041ff92582c2af8818440 to your computer and use it in GitHub Desktop.
Tabs Component
import React from "react";
import { render } from "react-dom";
const App = () => (
<Tabs>
<TabList>
<Tab>Tab 1</Tab>
<Tab>Tab 2</Tab>
<Tab>Tab 3</Tab>
</TabList>
<TabPanels>
<TabPanel>Content of Tab 1</TabPanel>
<TabPanel>Content of Tab 2</TabPanel>
<TabPanel>Content of Tab 3</TabPanel>
</TabPanels>
</Tabs>
);
const Tab = props => {
const { children, isActive, onActivate, isDisabled } = props;
return (
<li
onClick={isDisabled ? null : () => onActivate()}
style={
isDisabled ? { color: "#999" } : isActive ? { fontWeight: "bold" } : {}
}
>
<button disabled={isDisabled}>{children}</button>
</li>
);
};
const TabList = props => {
const { activeTabIndex, onActivateTab } = props;
const children = React.Children.map(props.children, (child, index) => {
return React.cloneElement(child, {
onActivate: () => {
onActivateTab(index);
},
isActive: activeTabIndex === index
});
});
return <ul>{children}</ul>;
};
const TabPanels = props => {
const { activeTabIndex } = props;
return <div>{props.children[activeTabIndex]}</div>;
};
const TabPanel = props => {
return <div>{props.children}</div>;
};
class Tabs extends React.Component {
constructor() {
super();
this.state = {
activeTabIndex: 0
};
this.handleOnActivateTab = this.handleOnActivateTab.bind(this);
}
handleOnActivateTab(index) {
this.setState({
activeTabIndex: index
});
}
render() {
const children = React.Children.map(this.props.children, child => {
return React.cloneElement(child, {
onActivateTab: this.handleOnActivateTab,
...this.state
});
});
return <div>{children}</div>;
}
}
render(<App />, document.getElementById("root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment