'underlined active page on navbar and scroll to footer on contacts react-bootstrap
I have a react-bootstrap navbar that has links to other pages. I want the nav-link of the page the user is in (active) to be underlined. I add some css that works for nav items with the "href='#home'" (ashtag) but not with the real links.
<Nav defaultActiveKey={"/"} >
<Nav.Link href="/">Home</Nav.Link>
<Nav.Link
href="/beafounder"
>
Be a founder
</Nav.Link>
<Nav.Link href="/portfolio" >Portfolio</Nav.Link>
</Nav>
<Navbar.Brand href="/">
<Logo />
</Navbar.Brand>
</Navbar.Collapse>
</div>
<div className="navDx">
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
<Nav.Link href="#home" >Team</Nav.Link>
<Nav.Link href="#link" >About Us</Nav.Link>
<Nav.Link href="#contacts">Contacts</Nav.Link>
</Nav>
I tried to add event keys to the nav link and change the defaultActiveKey but nothing, the nav item is underlined when i click it but the the active item remains the home.
.navbar-nav .nav-link.active {
border-bottom: 8px solid #D6FF0A !important; }
Solution 1:[1]
The active link get a class "active" so you can target it with following selector:
.nav-link.active {
text-decoration: underline;
}
Add event keys to all your links. Create a state to hold the active link. onSelect of Nav set the state:
const [activeLink, setActiveLink] = React.useState("home");
return (
<Navbar>
<Nav
defaultActiveKey={activeLink}
onSelect={(selectedKey, event) => {
event.preventDefault();
console.log("selected key is: ", selectedKey);
setActiveLink(selectedKey);
}}
>
<Nav.Link href="/" eventKey="home">
Home
</Nav.Link>
<Nav.Link href="/beafounder" eventKey="beafounder">
Be a founder
</Nav.Link>
<Nav.Link href="/portfolio" eventKey="portfolio">
Portfolio
</Nav.Link>
</Nav>
</Navbar>
I haven't integrated any router solution, that's why I'm canceling the event on select.
Please look into following sandbox: https://codesandbox.io/s/nifty-morning-mfcm5w
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Igor Gonak |
