DEV Community

Cover image for How to Create React Tabs with Tailwind CSS.
HyperCode for Devwares

Posted on • Updated on

How to Create React Tabs with Tailwind CSS.

React is a popular JavaScript library that allows developers to create complex user interfaces in a simple and efficient manner. Tailwind CSS is a utility-first CSS framework that makes it easy to create responsive and customizable user interfaces. In this blog, we will learn how to create React tabs using Tailwind CSS.

Prerequisites

  • Basic knowledge of React
  • Basic knowledge of Tailwind CSS
  • Node.js and NPM installed on your computer

Step 1: Create a new React app

To create a new React app, open your terminal and run the following command:

npx create-react-app react-tabs-tailwind
Enter fullscreen mode Exit fullscreen mode

This will create a new React app called react-tabs-tailwind.

Step 2: Install Tailwind CSS

To install Tailwind CSS, run the following command in your terminal:

npm install tailwindcss
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Tailwind CSS

Create a new file called tailwind.config.js in the root directory of your project and add the following code:

Copy code
module.exports = {
  mode: 'jit',
  purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}
Enter fullscreen mode Exit fullscreen mode

This will configure Tailwind CSS for your project.

Step 4: Add Tailwind CSS to your project

Open the index.css file in the src directory and add the following code:

Copy code
@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

This will add Tailwind CSS to your project.

Step 5: Create a new component called Tabs

Create a new file called Tabs.js in the src/components directory and add the following code:

import React, { useState } from 'react';

const Tabs = ({ children }) => {
  const [activeTab, setActiveTab] = useState(children[0].props.label);

  const handleClick = (e, newActiveTab) => {
    e.preventDefault();
    setActiveTab(newActiveTab);
  };

  return (
    <div className="max-w-md mx-auto">
      <div className="flex border-b border-gray-300">
        {children.map(child => (
          <button
            key={child.props.label}
            className={`${
              activeTab === child.props.label ? 'border-b-2 border-purple-500' : ''
            } flex-1 text-gray-700 font-medium py-2`}
            onClick={e => handleClick(e, child.props.label)}
          >
            {child.props.label}
          </button>
        ))}
      </div>
      <div className="py-4">
        {children.map(child => {
          if (child.props.label === activeTab) {
            return <div key={child.props.label}>{child.props.children}</div>;
          }
          return null;
        })}
      </div>
    </div>
  );
};

const Tab = ({ label, children }) => {
  return (
    <div label={label} className="hidden">
      {children}
    </div>
  );
};
export { Tabs, Tab };
Enter fullscreen mode Exit fullscreen mode

This component takes an array of tabs as a prop and renders the tab navigation and content.

Step 6: Create a new component called App

Open the App.js file in the src directory and replace the existing code with the following:

import React from 'react';
import { Tabs, Tab } from './Tabs';

const App = () => {
  return (
    <div>
      <Tabs>
        <Tab label="Tab 1">
          <div className="py-4">
            <h2 className="text-lg font-medium mb-2">Tab 1 Content</h2>
            <p className="text-gray-700">
              Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia, molestiae
              quas vel sint commodi repudiandae consequuntur voluptatum laborum numquam blanditiis
              harum quisquam eius sed odit fugiat iusto fuga praesentium optio, eaque rerum!
              Provident similique accusantium nemo autem. Veritatis obcaecati tenetur iure eius
              earum ut molestias architecto voluptate aliquam nihil, eveniet aliquid culpa officia
              aut! Impedit sit sunt quaerat, odit, tenetur error, harum nesciunt ipsum debitis quas
              aliquid. Reprehenderit, quia. Quo neque error repudiandae fuga? Ipsa laudantium
              molestias eos sapiente officiis modi at sunt excepturi expedita sint? Sed quibusdam
              recusandae alias error harum maxime adipisci amet laborum.
            </p>
          </div>
        </Tab>
        <Tab label="Tab 2">
          <div className="py-4">
            <h2 className="text-lg font-medium mb-2">Tab 2 Content</h2>
            <p className="text-gray-700">
              Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia, molestiae
              quas vel sint commodi repudiandae consequuntur voluptatum laborum numquam blanditiis
              harum quisquam eius sed odit fugiat iusto fuga praesentium optio, eaque rerum!
              Provident similique accusantium nemo autem. Veritatis obcaecati tenetur iure eius
              earum ut molestias architecto voluptate aliquam nihil, eveniet aliquid culpa officia
              aut! Impedit sit sunt quaerat, odit, tenetur error, harum nesciunt ipsum debitis quas
              aliquid. Reprehenderit, quia. Quo neque error repudiandae fuga? Ipsa laudantium
              molestias eos sapiente officiis modi at sunt excepturi expedita sint? Sed quibusdam
              recusandae alias error harum maxime adipisci amet laborum.
            </p>
          </div>
        </Tab>
        <Tab label="Tab 3">
          <div className="py-4">
            <h2 className="text-lg font-medium mb-2">Tab 3 Content</h2>
            <p className="text-gray-700">
              Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia, molestiae
              quas vel sint commodi repudiandae consequuntur voluptatum laborum numquam blanditiis
              harum quisquam eius sed odit fugiat iusto fuga praesentium optio, eaque rerum!
              Provident similique accusantium nemo autem. Veritatis obcaecati tenetur iure eius
              earum ut molestias architecto voluptate aliquam nihil, eveniet aliquid culpa officia
              aut! Impedit sit sunt quaerat, odit, tenetur error, harum nesciunt ipsum debitis quas
              aliquid. Reprehenderit, quia. Quo neque error repudiandae fuga? Ipsa laudantium
              molestias eos sapiente officiis modi at sunt excepturi expedita sint? Sed quibusdam
              recusandae alias error harum maxime adipisci amet laborum.
            </p>
          </div>
        </Tab>
      </Tabs>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this code, we've added some content to each Tab component using Tailwind CSS classes for styling. The content consists of a heading and a paragraph of text. When a tab is active, its content is displayed below the tab buttons. The Tabs component now maps over its children to find the active tab's content and renders it. Note that the Tab component itself is still hidden and only serves to define the label of each tab.

Step7: Rendering the content on the application

Now, we have to show the tabs we have created on our web page by rendering it on our index.js file.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

After rendering the application, our react Tabs with Tailwind css will look like the image below.

Tailwind react tab

Tailwind react tab 1

tailwind react tab 2

Conclusion

In conclusion, creating tabs in React with Tailwind CSS is a straightforward process that can be achieved by following a few simple steps.

First, you need to install the necessary packages such as react and tailwindcss. Next, you can create the Tab components and rendering it on the index.js file just luke we have done.

To style the tabs with Tailwind CSS, you can use utility classes such as border, rounded, and background color. You can also use hover, active, and focus variants to add interactive behavior to the tabs.

Overall, creating tabs in React with Tailwind CSS is a powerful way to create a user-friendly and visually appealing interface. With the help of the react and the flexibility of Tailwind CSS, you can easily customize the tabs to fit your specific design needs.

Resources

Top comments (0)