Logo
Published on

Creating Animated Tabs in React

Authors
  • Name
    Twitter

Introduction

Tab switching is a common UI design pattern found in web and mobile applications. It allows users to swiftly switch between different views or data sets without leaving the current page. This article focuses on implementing animated tab switching in a React application.

Feature Overview

  • Dynamic tab creation
  • Animated tab switching with an underline
  • Customizable underline length and position

Technology Stack

  • React
  • JavaScript
  • CSS

Implementation Steps

React Component Structure

First, let’s create a React component that includes a container for the tabs and the dynamic tab items.

import React, { useState } from 'react';  
  
const Tabs = ({ tabs }) => {  
  const [selectedTabIndex, setSelectedTabIndex] = useState(0);  
  const [underlineLeft, setUnderlineLeft] = useState(0);  
  
  const handleTabClick = (index) => {  
    const totalTabs = tabs.length;  
    const percentage = (index / totalTabs) * 100;  
    setSelectedTabIndex(index);  
    setUnderlineLeft(percentage);  
  };  
  
  return (  
    <div className="tab-container">  
      {tabs.map((tab, index) => (  
        <div  
          key={index}  
          className={`tab-item ${selectedTabIndex === index ? 'selected' : ''}`}  
          onClick={() => handleTabClick(index)}  
        >  
          {tab}  
        </div>  
      ))}  
      <div className="underline" style={{ left: `${underlineLeft}%` }}></div>  
    </div>  
  );  
};

CSS Styling

  1. Define styles for the tab items and container:
.tab-container {  
  display: flex;  
  position: relative;  
}  
  
.tab-item {  
  padding: 15px;  
  flex: 1;  
}  
  
.tab-item.selected {  
  color: #0052D9;  
}
  1. Define styles for the underline:
.underline {  
  position: absolute;  
  bottom: 0;  
  width: 16px;  
  height: 3px;  
  background-color: #0052D9;  
  transition: left 0.3s ease;  
  transform: translateX(-50%);  
}

Here, we use transform: translateX(-50%); to make sure the center of the underline aligns with the center of the selected tab.

Conclusion

By utilizing React, JavaScript, and CSS, we’ve successfully implemented an animated tab switching feature. The key takeaway is the usage of the CSS property transform: translateX(-50%); to accurately center the underline.

This approach is not only straightforward but also highly flexible, making it easy to apply to any application that requires tab-switching capabilities.