'React toggle tab className active/inactive
Can someone help me with an issue I'm having, I want to toggle the className active/inactive tab for styling purposes, but I don't know how. The functionality works, but I need the className to be active/inactive so I can style them properly. How can this be achieved?
Here is my code:
GlobalNav.jsx
import React, { useState } from "react";
import { CallToAction } from "core";
import Tabs from "../Tabs/Tabs";
import "./styles.scss";
const GlobalNav = ({ selectedTab }) => {
const activeTab = selectedTab.toLowerCase();
return (
<div>
<div className="global-nav">
{tabLinks[activeTab]?.map(item => {
return (
<CallToAction
as="button"
format="textOnly"
onClick={() => {}}
className="global-nav__button"
>
{item.title}
</CallToAction>
)})}
</div>
</div>
);
};
export default GlobalNav;
Tabs.jsx
import React, { useState } from "react";
import PropTypes from "prop-types";
import Tab from "./Tab/Tab.jsx";
import "./styles.scss";
const Tabs = ({ tabs, activeTab }) => {
const handleToggle = tab => {
activeTab(tab);
console.log('selected tab from Tabs', tab);
};
return (
<div className="tabs-container">
{tabs.map(tab => (
<Tab key={tab} tab={tab} onToggle={handleToggle} active={activeTab} />
))}
</div>
);
};
export default Tabs;
Tab.jsx
import React, { useState } from "react";
import classnames from 'classnames';
import "./styles.scss";
const Tab = ({ active, onToggle, tab }) => {
console.log(active === tab);
return (
<div className="tab-container">
<Button
as="button"
format="textOnly"
onClick={() => {
onToggle(tab);
}}
className={active === tab ? "tab-button-active" : "tab-button-inactive"}
>
{tab}
</Button>
</div>
);
};
export default Tab;
I've tried to define a state on Tabs and Tab components, but did not worked correctly, both tabs were selected on page load or when clicked stays both selected.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
