React applications often require a dynamic and interactive user interface to display content compactly and organized. One of the most common UI patterns to achieve this is using tabs. Tabs allow users to easily navigate between different views or datasets without leaving the current page.
In this blog, we will delve into the intricacies of implementing a tabs component in React applications, ensuring that our tabs are functional but also accessible and stylish.
At its core, a tabs component in a React app consists of a tab list and tab panels. The tab list serves as a container for tab components, each representing a clickable area where users can interact to switch tabs. When a tab is active, its corresponding panel containing the content associated with that tab is displayed.
React tabs are versatile and can be used in various scenarios, such as grouping related content, form steps, or a navigation component within your web app. It's crucial to manage the state of the active tab to ensure that the correct tab content is rendered and that the user experience remains seamless.
To implement tabs in React, developers often turn to the react-tabs package, which provides a set of pre-built components that are designed to work together harmoniously. This package includes the essential components like <Tabs>
, <TabList>
, <Tab>
, and <TabPanel>
, each playing a specific role in the tabs system.
Before diving into the tabs example, setting up our React environment is important. If you're starting a new project, you can create a react app using the following command:
1npx create-react-app my-tabs-app 2
Once your React application is ready, you can import the react-tabs package. This package is the backbone of our tabs component, providing the necessary building blocks to construct our tabs system. To import tabs into your project, execute the following command in your terminal:
1npm install --save react-tabs 2
With react-tabs installed, you can now start building your tabs component. In your components folder, create a new file for your tabs component, and import React along with the necessary parts from the react-tabs package:
1import React from 'react'; 2import { Tab, Tabs, TabList, TabPanel } from 'react-tabs'; 3import 'react-tabs/style/react-tabs.css'; 4
The above imports bring in the default styles for the tabs, ensuring that our tabs have a consistent look and feel right out of the box. However, you can customize the styles later to match your app's design requirements.
The structure of a tabs component is pivotal to its functionality. A well-organized tabs component provides a seamless user experience and ensures maintainability and scalability within your React application. Let's explore how to construct the foundational elements of our tabs component.
The tab list is the container that holds all the individual tab components. It acts as a navigational guide for users, allowing them to switch between different tab panels. Each tab component within the tab list represents a selectable item that, when clicked, makes its associated tab content panel visible.
Here's an example of how to set up a tab list with two tab components in a React function component:
1import React from 'react'; 2import { Tab, Tabs, TabList } from 'react-tabs'; 3 4const MyTabsComponent = () => { 5 return ( 6 <Tabs> 7 <TabList> 8 <Tab>First Tab</Tab> 9 <Tab>Second Tab</Tab> 10 </TabList> 11 </Tabs> 12 ); 13}; 14 15export default MyTabsComponent; 16
In the code snippet above, we create a functional component called MyTabsComponent. Inside it, we use the <Tabs>
component to wrap around a <TabList>
that contains two <Tab>
components. Each <Tab>
component is labeled accordingly, and this setup serves as the skeleton for our tabs component.
React applications often require a dynamic and interactive user interface to display content compactly and organized. One of the most common UI patterns to achieve this is using tabs. Tabs allow users to easily navigate between different views or datasets without leaving the current page.
In this blog, we will delve into the intricacies of implementing a tabs component in React applications, ensuring that our tabs are functional but also accessible and stylish.
At its core, a tabs component in a React app consists of a tab list and tab panels. The tab list serves as a container for tab components, each representing a clickable area where users can interact to switch tabs. When a tab is active, its corresponding panel containing the content associated with that tab is displayed.
React tabs are versatile and can be used in various scenarios, such as grouping related content, form steps, or a navigation component within your web app. It's crucial to manage the state of the active tab to ensure that the correct tab content is rendered and that the user experience remains seamless.
To implement tabs in React, developers often turn to the react-tabs package, which provides a set of pre-built components that are designed to work together harmoniously. This package includes the essential components like <Tabs>
, <TabList>
, <Tab>
, and <TabPanel>
, each playing a specific role in the tabs system.
Before diving into the tabs example, setting up our React environment is important. If you're starting a new project, you can create a react app using the following command:
1npx create-react-app my-tabs-app 2
Once your React application is ready, you can import the react-tabs package. This package is the backbone of our tabs component, providing the necessary building blocks to construct our tabs system. To import tabs into your project, execute the following command in your terminal:
1npm install --save react-tabs 2
With react-tabs installed, you can now start building your tabs component. In your components folder, create a new file for your tabs component, and import React along with the necessary parts from the react-tabs package:
1import React from 'react'; 2import { Tab, Tabs, TabList, TabPanel } from 'react-tabs'; 3import 'react-tabs/style/react-tabs.css'; 4
The above imports bring in the default styles for the tabs, ensuring that our tabs have a consistent look and feel right out of the box. However, you can customize the styles later to match your app's design requirements.
The structure of a tabs component is pivotal to its functionality. A well-organized tabs component provides a seamless user experience and ensures maintainability and scalability within your React application. Let's explore how to construct the foundational elements of our tabs component.
The tab list is the container that holds all the individual tab components. It acts as a navigational guide for users, allowing them to switch between different tab panels. Each tab component within the tab list represents a selectable item that, when clicked, makes its associated tab content panel visible.
Here's an example of how to set up a tab list with two tab components in a React function component:
1import React from 'react'; 2import { Tab, Tabs, TabList } from 'react-tabs'; 3 4const MyTabsComponent = () => { 5 return ( 6 <Tabs> 7 <TabList> 8 <Tab>First Tab</Tab> 9 <Tab>Second Tab</Tab> 10 </TabList> 11 </Tabs> 12 ); 13}; 14 15export default MyTabsComponent; 16
In the code snippet above, we create a functional component called MyTabsComponent. Inside it, we use the <Tabs>
component to wrap around a <TabList>
that contains two <Tab>
components. Each <Tab>
component is labeled accordingly, and this setup serves as the skeleton for our tabs component.
Once the tab list is in place, the next step is to design the tab content panels. Each tab panel is associated with a tab component and contains the content displayed when its corresponding tab is active.
Here's how you can add tab panels to the MyTabsComponent:
1import React from 'react'; 2import { Tab, Tabs, TabList, TabPanel } from 'react-tabs'; 3 4const MyTabsComponent = () => { 5 return ( 6 <Tabs> 7 <TabList> 8 <Tab>First Tab</Tab> 9 <Tab>Second Tab</Tab> 10 </TabList> 11 <TabPanel> 12 <div>Content for the First Tab</div> 13 </TabPanel> 14 <TabPanel> 15 <div>Content for the Second Tab</div> 16 </TabPanel> 17 </Tabs> 18 ); 19}; 20 21export default MyTabsComponent; 22
In this example, we've added two <TabPanel>
components immediately following the <TabList>
Each <TabPanel>
contains a <div>
with placeholder content. When a tab is selected, its corresponding <TabPanel>
will be displayed, and the content within that panel will be rendered on the page.
By default, the react-tabs package ensures that only the content of the active tab is rendered, optimizing performance by avoiding unnecessary rendering of hidden content. However, if you need all tab panels mounted in the DOM, use the forceRenderTabPanel prop on the <Tabs>
component or the forceRender prop on individual <TabPanel>
components.
The visual appeal and usability of a tabs component are just as important as its functionality. Proper styling can make the tabs more intuitive and enjoyable to use. Let's look at how to apply CSS to enhance the appearance of our tabs and ensure they provide a great user experience.
The react-tabs package comes with default styles that provide a basic look and feel for the tabs. However, you can customize these styles to align the tabs with your brand or design guidelines. You can create a CSS file for your tabs component and import it into your React component.
Here's an example of how you might style the tabs and the active tab:
1/* TabsComponent.css */ 2.react-tabs { 3 font-family: 'Arial', sans-serif; 4} 5 6.react-tabs__tab-list { 7 border-bottom: 2px solid #ccc; 8 padding-left: 0; 9} 10 11.react-tabs__tab { 12 display: inline-block; 13 list-style: none; 14 padding: 10px 20px; 15 cursor: pointer; 16 border: 1px solid transparent; 17 border-bottom: none; 18 margin-bottom: -2px; 19} 20 21.react-tabs__tab--selected { 22 background-color: #fff; 23 border-color: #aaa; 24 color: #333; 25 border-radius: 5px 5px 0 0; 26} 27 28.react-tabs__tab:focus { 29 box-shadow: 0 0 5px hsl(208, 99%, 50%); 30 border-color: hsl(208, 99%, 50%); 31 outline: none; 32} 33 34.react-tabs__tab-panel { 35 padding: 16px; 36 border: 1px solid #aaa; 37 background-color: #fff; 38} 39
In this CSS file, we've added some custom styles to the tabs. We've given the tab list a bottom border to separate it from the content, styled each tab to look like a button, and provided a distinct look for the active tab using the .react-tabs__tab--selected class. We've also included focus styles to improve accessibility, ensuring that users navigating with a keyboard can easily identify which tab is focused.
To apply these styles to your tabs component, import the CSS file into your React component:
1import './TabsComponent.css'; 2
Sometimes, you can control the width of the tabs to fit the design of your page or to handle responsiveness. The width of the tabs can be managed through CSS, either by setting a fixed width or using flexible sizing with CSS flexbox or grids.
For example, to ensure that the tabs take up the entire width of their container, you could use the following CSS:
1.react-tabs__tab-list { 2 display: flex; 3} 4 5.react-tabs__tab { 6 flex-grow: 1; 7 text-align: center; 8} 9
This CSS will cause each tab to grow and fill the available space, dividing the width equally among all tabs. The text-align: center; style ensures that the tab titles are centered within each tab.
The true power of a tabs component in a React application lies in its interactivity. Users expect to click on a tab and see the corresponding content panel without delay or issues. To achieve this seamless interaction, we need to manage the state of the active tab effectively. React's state management capabilities, particularly hooks, make this task straightforward.
React hooks allow us to manage state in functional components without writing a class. The useState hook is handy for tracking which tab is currently active. When a user clicks on a tab, we can update this state to render the appropriate tab content.
Here's an example of how you might use the useState hook to manage the active tab state:
1import React, { useState } from 'react'; 2import { Tab, Tabs, TabList, TabPanel } from 'react-tabs'; 3import './TabsComponent.css'; 4 5const MyTabsComponent = () => { 6 const [activeIndex, setActiveIndex] = useState(0); 7 8 return ( 9 <Tabs selectedIndex={activeIndex} onSelect={index => setActiveIndex(index)}> 10 <TabList> 11 <Tab>First Tab</Tab> 12 <Tab>Second Tab</Tab> 13 </TabList> 14 <TabPanel> 15 <div>Content for the First Tab</div> 16 </TabPanel> 17 <TabPanel> 18 <div>Content for the Second Tab</div> 19 </TabPanel> 20 </Tabs> 21 ); 22}; 23 24export default MyTabsComponent; 25
In the above code, activeIndex is the state that keeps track of the currently active tab, and setActiveIndex is the function we call to update this state. We initialize activeIndex with a value of 0, which means the first tab will be active by default on the initial render.
The Tabs component from react-tabs accepts a selectedIndex prop, which determines which tab is currently selected, and an onSelect prop, a function that gets called with the new index when a tab is selected. By passing activeIndex and setActiveIndex to these props, we create a controlled component that responds to user interactions.
In addition to simply clicking on tabs to switch them, you can provide additional functionality for users to switch tabs. For instance, you could implement buttons to navigate to the next or previous tab, or even set up keyboard shortcuts for power users.
Here's an example of how you could add buttons to navigate between tabs:
1const MyTabsComponent = () => { 2 const [activeIndex, setActiveIndex] = useState(0); 3 const tabTitles = ['First Tab', 'Second Tab']; 4 5 const goToNextTab = () => { 6 setActiveIndex((prevIndex) => (prevIndex + 1) % tabTitles.length); 7 }; 8 9 const goToPreviousTab = () => { 10 setActiveIndex((prevIndex) => (prevIndex - 1 + tabTitles.length) % tabTitles.length); 11 }; 12 13 return ( 14 <> 15 <button onClick={goToPreviousTab} disabled={activeIndex === 0}> 16 Previous Tab 17 </button> 18 <button onClick={goToNextTab} disabled={activeIndex === tabTitles.length - 1}> 19 Next Tab 20 </button> 21 <Tabs selectedIndex={activeIndex} onSelect={index => setActiveIndex(index)}> 22 <TabList> 23 {tabTitles.map((title, index) => ( 24 <Tab key={index}>{title}</Tab> 25 ))} 26 </TabList> 27 <TabPanel> 28 <div>Content for the First Tab</div> 29 </TabPanel> 30 <TabPanel> 31 <div>Content for the Second Tab</div> 32 </TabPanel> 33 </Tabs> 34 </> 35 ); 36}; 37
In this example, we've added two buttons: one to go to the previous tab and one to go to the next tab. We've also added some logic to wrap around the tabs if the user is at the first or last tab. The disabled prop on the buttons prevents users from navigating beyond the available tabs.
Once the basic functionality of the tabs component is in place, we can enhance it by adding more sophisticated features. These enhancements can improve the user experience by providing greater flexibility and ensuring that our tabs are accessible to all users, including those using assistive technologies.
Sometimes, you can prevent users from selecting particular tabs until specific conditions are met. This is where disabled tabs come into play. The react-tabs package allows you to disable any tab easily by using the disabled prop.
Here's how you can disable a tab:
1<Tab disabled>Disabled Tab</Tab> 2
In addition to disabling tabs, you can create custom components to replace or wrap the default tab components provided by react-tabs. This is useful when you must add extra functionality or styling that is not supported out of the box.
For example, you could create a custom tab component that includes an icon:
1const CustomTab = ({ title, icon }) => ( 2 <Tab> 3 <img src={icon} alt={`${title} icon`} /> 4 {title} 5 </Tab> 6); 7 8CustomTab.tabsRole = 'Tab'; // Required to integrate with react-tabs 9
When using custom components, assign the appropriate tabsRole to inform react-tabs of the component's role within the tabs system.
Accessibility is a crucial aspect of web development, and it's essential to ensure that our tabs are usable by everyone, including people who rely on keyboard navigation or screen readers.
The react-tabs package provides built-in support for keyboard navigation out of the box. Users can navigate between tabs using the arrow keys and select a tab by pressing the Enter key. However, you can further enhance accessibility by following these additional considerations:
Here's an example of how you might customize focus styles for better keyboard navigation:
1.react-tabs__tab:focus { 2 outline: none; 3 box-shadow: 0 0 0 3px -webkit-focus-ring-color; 4} 5
In conclusion, tabs are essential in modern web design, offering a streamlined and organized way to present information. Throughout this guide, we've taken a deep dive into creating a functional and stylish tabs component within a React application. Using the react-tabs package, we've demonstrated how to construct, style, and manage tabs effectively while considering accessibility and interactivity.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.