React :: Tab

Renders a tabbed menu and view component.

Define a TabItem component, pass it to the Tab and remove unnecessary nodes expect for TabItem by identifying the function’s name in props.children. Use the React.useState() hook to initialize the value of the bindIndex state variable to props.defaultIndex. Use on the collected nodes to render the tab-menu and tab-view. Define changeTab, which will be executed when clicking a <button> from the tab-menuchangeTab executes the passed callback, onTabClick and updates bindIndex, which in turn causes a re-render, evaluating the style and className of the tab-view items and tab-menu buttons according to their index.

.tab-menu > button {
  cursor: pointer;
  padding: 8px 16px;
  border: 0;
  border-bottom: 2px solid transparent;
  background: none;
.tab-menu > button.focus {
  border-bottom: 2px solid #007BEF;
.tab-menu > button:hover {
  border-bottom: 2px solid #007BEF;
function TabItem(props) {
  return <div {...props} />;

function Tabs(props) {
  const [bindIndex, setBindIndex] = React.useState(props.defaultIndex);
  const changeTab = newIndex => {
    if (typeof props.onTabClick === "function") props.onTabClick(newIndex);
  const items = props.children.filter(item => === "TabItem");

  return (
    <div className="wrapper">
      <div className="tab-menu">
        {{ props: { index, label } }) => (
            onClick={() => changeTab(index)}
            className={bindIndex === index ? "focus" : ""}
      <div className="tab-view">
        {{ props }) => (
            style={{ display: bindIndex === props.index ? "block" : "none" }}
  <Tabs defaultIndex="1" onTabClick={console.log}>
    <TabItem label="A" index="1">
      Lorem ipsum
    <TabItem label="B" index="2">
      Dolor sit amet

Leave a Reply

Your email address will not be published. Required fields are marked *