I am working with Reactjs using html, css, and javascript. I want to style active navigator item in the navbar with white border. That is mean the border will stay in the item while the page of this item is open.
import React, { useState } from "react";
import { Link } from "react-router-dom";
import "./Navbar.css";
import { navItems } from "./NavItems";
import Dropdown from "./Dropdown";
function Navbar() {
const [dropdown, setDropdown] = useState(false);
return (
<>
<nav className="navbar">
<ul className="nav-items">
{navItems.map((item) => {
if (item.id === "C3") {
return (
<li
key={item.id}
className={item.cName}
id={window.location.pathname === item.path? "C10":""}
onm ouseClick={() => setDropdown(true)}
onm ouseEnter={() => setDropdown(true)}
onm ouseLeave={() => setDropdown(false)}
>
<Link to={item.title}>{item.title}</Link>
{dropdown && <Dropdown />}
</li>
);
}
return (
<li key={item.id}
className={item.cName}
id={window.location.pathname === item.path? "C10":""}
>
<Link to={item.path}>{item.title}</Link>
</li>
);
})}
</ul>
</nav>
</>
);
}
export default Navbar;
This is the CSS file
.nav-item a:hover {
border: solid 2px white;
}
#C10{
border: solid 2px white;
}
I try to use this method in CSS file.
.nav-item a:active {
border: solid 2px white;
}
and I use this method in CSS file and JS file also but it does not work!
id={window.location.pathname === item.path? "C10":""}
#C10{
border: solid 2px white;
}
CodePudding user response:
If you want to style an active <Link/>
you have to use a <Navlink/>
instead.
Check the doc: https://reactrouter.com/en/main/components/nav-link
CodePudding user response:
As William said you are better off using the actual <NavLink/>
elements then programming plain html in React. However you can also create a function that adds the active class to the li
item when it's selected.
See this example:
const links = ['https://google.com', 'https://google.be', 'https://google.nl'];
const [active, setActive] = useState(null);
<ul>
{links.map((link) => (
<li className="nav-item">
<a
href={`#${link}`}
className={`nav-link ${active == link && 'm-active'}`}
onClick={() => setActive(link)}
>{link}</a>
</li>
))}
</ul>