Verticle tabs in Reactjs

2023-02-25

To create vertical tabs in a sidebar using React functional components, you can follow these general steps:

  • Define a state variable to keep track of the active tab. This will allow you to switch between tabs when the user clicks on them.

  • Create a function that will be called when a tab is clicked. This function will update the state variable to reflect the currently active tab.

  • Define an array of tab objects, where each object represents a tab and includes the tab's title and content. This array will be used to generate the tabs and their content.

  • Use the map() function to generate the tab elements based on the array of tab objects. For each tab, create a button element that will serve as the tab's title and set its onClick property to the function created in step 2.

  • Create a div element for each tab's content and conditionally render it based on the active tab state variable.

  • Style the tabs and content to achieve the desired appearance and layout.

Here is some example code that demonstrates these steps:

import { useState } from "react";

function VerticalTabs() {
  const [activeTab, setActiveTab] = useState(0);

  const handleTabClick = (index) => {
    setActiveTab(index);
  };

  const tabs = [
    { title: "Tab 1", content: "Content for tab 1" },
    { title: "Tab 2", content: "Content for tab 2" },
    { title: "Tab 3", content: "Content for tab 3" },
  ];

  return (
    <div className="sidebar">
      {tabs.map((tab, index) => (
        <button
          key={index}
          className={activeTab === index ? "active" : ""}
          onClick={() => handleTabClick(index)}
        >
          {tab.title}
        </button>
      ))}
      {tabs.map((tab, index) => (
        <div
          key={index}
          className={activeTab === index ? "content active" : "content"}
        >
          {tab.content}
        </div>
      ))}
    </div>
  );
}

In this example, the tabs are created using a button element with the tab title as its content. The active tab is highlighted using a CSS class. The content for each tab is rendered in a div element, and the active tab's content is conditionally rendered based on the active tab state variable. Note that the CSS styles for this component are not included in this example, but they should be defined to achieve the desired appearance and layout.