When we browse the internet and visit multiple websites in the same browser, we see different tabs open up as we go to new sites. Sometimes, we also need tabs in our own website to help clients navigate to new pages or display different content. For basic HTML sites, we can use vanilla CSS to add tabs, but we also need JavaScript to make the tabs functional.
In this article, we will focus on how to add tabs to a React website. We will cover two different methods:
1. Using DaisyUI
If we are using Tailwind CSS for styling our website, we can use DaisyUI. DaisyUI gives us the flexibility to use pre-built components. Instead of writing multiple classes to style each component, we can simply plug in the components.
To use DaisyUI, we first need to install it in our React project by running the following command:
npm i -D daisyui@latest
Next, in the tailwind.config.js
file, add the following:
module.exports = {
//…
plugins: [
require(‘daisyui’),
],
}
Now, browse the DaisyUI website and find the component named “Tab.” You will be able to see multiple tab options. Choose any tab style, click on the JSX option, copy the code, and paste it into your website.
2. Using Awesome React Components
For the second method, we will use the Awesome React Components repository. Go to this link. Search for “Tabs,” then select React Tabs. You’ll find instructions on how to install and use it.
To install, run the following command in your terminal:
npm install –save react-tabs
import ‘react-tabs/style/react-tabs.css’;
<Tabs>
<TabList>
<Tab>Title 1</Tab>
<Tab>Title 2</Tab>
</TabList>
<TabPanel>
<h2>Any content 1</h2>
</TabPanel>
<TabPanel>
<h2>Any content 2</h2>
</TabPanel>
</Tabs>
This code will create two tabs labeled “Title 1” and “Title 2.” When we click on a tab, the corresponding content will be displayed. Inside the <TabPanel>
, we can insert any content we want to display on our website. For example, we could display different types of cards based on food categories.