Creating a tab component in React

In this tutorial we’ll be building a tab component in React. Tab components allow you to break complex interfaces into smaller subsections that are easy to navigate between. Tabs are a commonly used UI element so having an understanding of how they wor…


This content originally appeared on DEV Community and was authored by Michael Burrows

In this tutorial we’ll be building a tab component in React. Tab components allow you to break complex interfaces into smaller subsections that are easy to navigate between. Tabs are a commonly used UI element so having an understanding of how they work in React is quite beneficial.

For the purposes of this tutorial we’ll setup a project using Create React App by running the following command:

npx create-react-app react-tabs

Once the setup is complete create a new /src/components folder with a Tab.js file and tab.css file.

We’ll now create the basic structure for the tab component in the Tab.js file:

import React, { useState } from "react";
import "./tabs.css";

const Tabs = () => { 
  return (
    <>
     <h1>Hello World</h1>
    </>
  );
};

export default Tabs;

Now let’s load the component by editing the App.js file as follows:

import "./App.css";
import Tabs from "./components/Tabs";

const App = () => {
  return (
    <div className="App">
      <Tabs />
    </div>
  );
}

export default App;

Test to see that the component had been loaded successfully then move onto the next step.

Back to the Tab.js file let’s first declare the required variables:

import React, { useState } from "react";
import "./tabs.css";

const Tabs = () => {
  const [activeIndex, setActiveIndex] = useState(1);
  const handleClick = (index) => setActiveIndex(index);
  const checkActive = (index, className) => activeIndex === index ? className : "";
  return (
    <>
      <h1>Hello World</h1>
    </>
  );
};

export default Tabs;

  • activeIndex – contains the index of active tab, in our case 1,2, or 3.
  • handleClick – sets the active index when a tab is clicked.
  • checkActive – adds the active class for styling and toggling visibility.

We can now add the HTML markup starting with the clickable tab elements:

const Tabs = () => {
  const [activeIndex, setActiveIndex] = useState(1);
  const handleClick = (index) => setActiveIndex(index);
  const checkActive = (index, className) => activeIndex === index ? className : "";
  return (
    <>
      <div className="tabs">
        <button
          className={`tab ${checkActive(1, "active")}`}
          onClick={() => handleClick(1)}
        >
          Product Info
        </button>
        <button
          className={`tab ${checkActive(2, "active")}`}
          onClick={() => handleClick(2)}
        >
          Customer Reviews
        </button>
        <button
          className={`tab ${checkActive(3, "active")}`}
          onClick={() => handleClick(3)}
        >
          Delivery &amp; Returns
        </button>
      </div>      
    </>
  );
};

And the panels that contain the content:

const Tabs = () => {
  const [activeIndex, setActiveIndex] = useState(1);
  const handleClick = (index) => setActiveIndex(index);
  const checkActive = (index, className) => activeIndex === index ? className : "";
  return (
    <>
      <div className="tabs">
        <button
          className={`tab ${checkActive(1, "active")}`}
          onClick={() => handleClick(1)}
        >
          Product Info
        </button>
        <button
          className={`tab ${checkActive(2, "active")}`}
          onClick={() => handleClick(2)}
        >
          Customer Reviews
        </button>
        <button
          className={`tab ${checkActive(3, "active")}`}
          onClick={() => handleClick(3)}
        >
          Delivery &amp; Returns
        </button>
      </div>
      <div className="panels">
        <div className={`panel ${checkActive(1, "active")}`}>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean erat ligula, feugiat at felis vitae, porttitor lacinia quam.</p>
        </div>
        <div className={`panel ${checkActive(2, "active")}`}>
          <p>Nulla lobortis quis massa quis lobortis. Nullam porta semper lorem, vel efficitur augue rutrum quis. Suspendisse potenti.</p>
        </div>
        <div className={`panel ${checkActive(3, "active")}`}>
          <p>Cras porta consectetur dolor porttitor fringilla. Cras vitae urna ac erat fermentum egestas. Donec egestas cursus scelerisque.</p>
        </div>
      </div>
    </>
  );
};

Now we just need to add the CSS as follows:

.tabs {  
  display: flex;  
}
.tab {  
  justify-content: center;
  align-items: center;
  width: 100%;
  background: lightsteelblue; 
  padding: 2em 0;  
  border: none;
}
.tab:not(:last-child) {
  border-right: 1px solid steelblue;  
}
.tab.active {
  background: steelblue;
  font-weight: bold;
}
.panel {
  display: none;
  background-color: #eaeaea;
  padding: 10px;
}
.panel.active {
  display: block;
}

That’s all for this tutorial. You should now have a working tab component that’s can easily be dropped into a React application. If you’re interested in learning more about building custom React components check out all our full collection of React tutorials.


This content originally appeared on DEV Community and was authored by Michael Burrows


Print Share Comment Cite Upload Translate Updates
APA

Michael Burrows | Sciencx (2023-03-10T00:01:49+00:00) Creating a tab component in React. Retrieved from https://www.scien.cx/2023/03/10/creating-a-tab-component-in-react/

MLA
" » Creating a tab component in React." Michael Burrows | Sciencx - Friday March 10, 2023, https://www.scien.cx/2023/03/10/creating-a-tab-component-in-react/
HARVARD
Michael Burrows | Sciencx Friday March 10, 2023 » Creating a tab component in React., viewed ,<https://www.scien.cx/2023/03/10/creating-a-tab-component-in-react/>
VANCOUVER
Michael Burrows | Sciencx - » Creating a tab component in React. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/03/10/creating-a-tab-component-in-react/
CHICAGO
" » Creating a tab component in React." Michael Burrows | Sciencx - Accessed . https://www.scien.cx/2023/03/10/creating-a-tab-component-in-react/
IEEE
" » Creating a tab component in React." Michael Burrows | Sciencx [Online]. Available: https://www.scien.cx/2023/03/10/creating-a-tab-component-in-react/. [Accessed: ]
rf:citation
» Creating a tab component in React | Michael Burrows | Sciencx | https://www.scien.cx/2023/03/10/creating-a-tab-component-in-react/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.