Reputation: 33
I have a Navbar with tabs, and I want to make a function called onClick that gets the event, and adds a class to that tab "active". But, when I click another tab, it should remove a class from the previous tab and add it to that one.
Sample of my code:
const [clickedTab, setClickedTab] = useState(true);
function Click() {
if (clickedTab === true) {
console.log(clickedTab);
tab.classList.add("active");
}
else {
console.log("Error!");
}
}
Upvotes: 0
Views: 313
Reputation: 5380
Here is a simple example so you can get the idea; we hold current active element id in a state
then based on that we decide what class name it should have; no need to use classList
's add
or remove
function Header () {
const [active, setActive] = React.useState();
return (
<header>
<ul>
<li
className={active === 1? "red":"blue"}
onClick={()=>setActive(1)}
>a</li>
<li
className={active === 2? "red":"blue"}
onClick={()=>setActive(2)}
>b</li>
<li
className={active === 3? "red":"blue"}
onClick={()=>setActive(3)}
>c</li>
</ul>
</header>
);
}
ReactDOM.render( <Header />, app );
.red{background:red}.blue{background:blue}li{color:#fff;width:30px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>
Upvotes: 0
Reputation: 191986
In React use the model (via useState()
in this case) to make changes to the view.
Set the activeId
of the tab in the state, and if the tab's id
is equal to activeId
pass set it's active
to true
. The tab itself can add/remove the className
.
const { useState } = React;
const Tab = ({ id, active, setActive }) => (
<li
className={`tab ${active ? 'active' : ''}`}
onClick={() => setActive(id)}
>
{id}
</li>
);
const Example = ({ tabs }) => {
const [activeId, setActive] = useState();
return (
<ul className="tabs">
{tabs.map(id => (
<Tab
key={id}
id={id}
setActive={setActive}
active={id === activeId}
/>
))}
</ul>
);
}
const tabs = [1, 2, 3, 4];
ReactDOM.render(
<Example tabs={tabs} />,
root
);
.tabs {
display: flex;
list-style: none;
}
.tab {
height: 1em;
width: 2em;
border: 1px solid red;
text-align: center;
cursor: pointer;
}
.active {
background: red;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
Upvotes: 1