I want to change some styles of the text of the tab for my navbar. I want to switch between pages whenever I click the on the tab. And for that I want that tab to be active. I have written code as:
Header.js
JavaScript
x
19
19
1
import React from "react";
2
import "./Header.css";
3
import Tab from "./Tab";
4
5
const tabs = ["About", "Portfolio", "Blogs", "Contact"];
6
7
const Header = () => {
8
const
9
return (
10
<div className="header">
11
{tabs.map((elem, indx) => {
12
return <Tab key={indx} text={elem} />;
13
})}
14
</div>
15
);
16
};
17
18
export default Header;
19
Header.css
JavaScript
1
13
13
1
.header {
2
width: 100%;
3
background-color: transparent;
4
z-index: 1;
5
color: white;
6
padding: 1em;
7
box-shadow: 2px 2px 2px 2px rgb(66, 65, 65);
8
9
display: flex;
10
gap: 2em;
11
justify-content: flex-end;
12
}
13
Tab.js
JavaScript
1
19
19
1
import React, { useState } from "react";
2
import "./Tab.css";
3
4
const Tab = ({ text }) => {
5
const [active, setActive] = useState(false);
6
7
return (
8
<div className="tab">
9
<div
10
className={`text ${active && "active"}`}
11
onClick={() => setActive(true)}>
12
{text}
13
</div>
14
</div>
15
);
16
};
17
18
export default Tab;
19
Tab.css
JavaScript
1
18
18
1
.tab {
2
padding: 0.3;
3
}
4
5
.text {
6
font-size: 1.1rem;
7
}
8
9
.active {
10
color: chocolate;
11
border-bottom: 1px solid chocolate;
12
}
13
14
.text:hover {
15
color: chocolate;
16
cursor: pointer;
17
}
18
Now when I click the tab it becomes active and clicking another tab make both of them active but I want only one to be active. How can I change the code in order to achieve what I want?
Advertisement
Answer
You have to lift the active tab state from the Tab
component to the Header
one and set a callback that will be passed to the Tab
component, in order to update the state in the parent.
You should end up with something like:
JavaScript
1
31
31
1
const tabs = ['About', 'Portfolio', 'Blogs', 'Contact']
2
3
const Header = () => {
4
const [activeTab, setActiveTab] = useState('');
5
6
const handleTabClick = useCallback((tab) => {
7
setActiveTab(tab);
8
}, []);
9
10
return (
11
<div className="header">
12
{tabs.map((elem) => {
13
return <Tab key={elem} text={elem} isActive={elem === activeTab} onTabClick={handleTabClick} />;
14
})}
15
</div>
16
);
17
}
18
19
const Tab = ({ text, isActive, onTabClick }) => {
20
return (
21
<div className="tab">
22
<div
23
className={`text ${isActive && "active"}`}
24
onClick={() => onTabClick(text)}
25
>
26
{text}
27
</div>
28
</div>
29
);
30
}
31