I would like to know the way to activate and underline a specific tab/item in the Nav Bar when a button outside the Nav Bar is clicked in ReactJS
Currently, this is what I did to activate and underline the item in the Nav Bar when a Nav Bar item is clicked.
Navbar.jsx
<Navbar bg="light" variant="light" sticky="top">
<Container fluid>
<Navbar.Brand href="home" style={{ width: "20%" }}>
<img
className="logo"
src="/images/logo.png"
width={50}
height={50}
alt=""
style={{
margin: "auto",
display: "flex",
justifyContent: "center",
}}
/>
</Navbar.Brand>
<Nav style={{ width: "100%", justifyContent: "space-evenly" }}>
<Nav.Link
className="navLink"
style={{ width: "20%", textAlign: "center" }}
onClick={() => {
navigate("/home");
sessionStorage.setItem("navItem", "home");
}}
>
<span
style={
sessionStorage.getItem("navItem") === "home"
? { borderBottom: "2px solid #FFC0CB" }
: {}
}
>
Home
</span>
</Nav.Link>
<Nav.Link
className="navLink"
style={{ width: "20%", textAlign: "center" }}
onClick={() => {
navigate("/booking");
sessionStorage.setItem("navItem", "booking");
}}
>
<span
style={
sessionStorage.getItem("navItem") === "booking"
? { borderBottom: "2px solid #FFC0CB" }
: {}
}
>
Booking
</span>
</Nav.Link>
</Nav>
</Container>
</Navbar>
I was wondering how it should be done in a case where I have a button somewhere in the Body. For example, a "Manage Booking" button, so when I click that button, it should activate and underline the "Booking" item in the Nav Bar. Currently, when clicking the "Manage Booking" button, it navigates to the Booking page but the "Home" item in the Nav bar is still underlined.
<button
className="bookingBtn"
onClick={() => navigate("/booking")}>
Manage Booking
</button>
CodePudding user response:
To manage the state of component outside the component, you could pass the state as a prop. But that's good enough only if you're passing prop from parent to children. Otherwise code could get really messy really fast. You need global state here, which will be accessible from everywhere in your app. You could use redux for this.
CodePudding user response:
When your navigating from anywhere else set the navItem property in the session storage.
<button
className="bookingBtn"
onClick={() => {
sessionStorage.setItem("navItem", "booking");
navigate("/booking");
}}
>
Manage Booking
</button>;