Question
Answer and Explanation
Setting the active tab in React JS typically involves managing state to track which tab is currently selected. Here's a breakdown of how to achieve this:
1. State Management:
- Use React's `useState` hook to maintain the active tab's index or identifier. This state will determine which tab is visually highlighted as active.
2. Tab Component Structure:
- Create a component to represent each tab. This component should receive a prop indicating whether it's active or not.
3. Click Handlers:
- Attach click handlers to each tab. When a tab is clicked, update the state to reflect the newly selected tab.
4. Conditional Rendering:
- Use conditional rendering to apply different styles or classes to the active tab, visually distinguishing it from the others.
5. Example Code:
import React, { useState } from 'react';
function Tabs() {
const [activeTab, setActiveTab] = useState(0);
const tabs = [
{ id: 0, label: 'Tab 1', content: 'Content for Tab 1' },
{ id: 1, label: 'Tab 2', content: 'Content for Tab 2' },
{ id: 2, label: 'Tab 3', content: 'Content for Tab 3' },
];
const handleTabClick = (id) => {
setActiveTab(id);
};
return (
<div>
<div className="tab-headers">
{tabs.map((tab) => (
<button
key={tab.id}
className={activeTab === tab.id ? 'active' : ''}
onClick={() => handleTabClick(tab.id)}
>
{tab.label}
</button>
))}
</div>
<div className="tab-content">
<p>{tabs[activeTab].content}</p>
</div>
</div>
);
}
export default Tabs;
6. Styling:
- Add CSS to style the active tab differently. For example, you might change its background color or font weight.
By following these steps, you can effectively manage and display the active tab in your React application. This approach ensures a smooth and intuitive user experience when navigating between tabs.