I have a strong foundation in HTML and CSS/SASS but I'm just getting started with React. Recently, I encountered an issue that has me stumped.
I am trying to highlight a button on the navigation bar based on the current page the user is on.
I attempted to add a simple onClick event handler to the buttons which would trigger a function passing in a string like "home" or "contact".
After adding an alert() to the function for testing, I noticed that upon loading the page, every button's method was called resulting in multiple alerts. Subsequently, clicking the buttons seemed ineffective as if the onClick event was never added.
Could someone please point out where I might be going wrong with this straightforward function? I've been grappling with it for the past few hours and would greatly appreciate any insights.
Thank you!
NavBar.js:
function NavBar() {
const isActive = "home";
return (
<nav className="landing-page__nav-bar nav-bar">
<ul className="nav-bar__list">
<Link to ='/home'><li><a data-page="home" className="home-link">
<button href="landingpage" className={` ${isActive === "home" ? 'btn__nav-bar-btn active-link' : 'btn__nav-bar-btn'}`} onClick={buttonWasClicked("home")}>Home</button>
</a></li>
</Link>
<Link to ='/portfolio'><li><a data-page="portfolio" className="portfolio-link">
<button className={` ${isActive === "portfolio" ? 'btn__nav-bar-btn active-link' : 'btn__nav-bar-btn'`} } onClick={buttonWasClicked("portfolio")}>Portfolio</button>
</a></li>
</Link>
<Link to ='/artwork'><li><a data-page="doodles" className="doodles-link">
<button className={` ${isActive === "artwork" ? 'btn__nav-bar-btn active-link' : 'btn__nav-bar-btn'}`} onClick={buttonWasClicked("artwork")}>Artwork</button>
</a></li></Link>
<Link to ='/photography'><li><a data-page="photography" className="photography-link">
<button className={` ${isActive === "photography" ? 'btn__nav-bar-btn active-link' : 'btn__nav-bar-btn'}`} onClick={buttonWasClicked("photography")}>Photography</button>
</a></li></Link>
<Link to ='/cv'><li><a data-page="cv" className="cv-link">
<button className={` ${isActive === "cv" ? 'btn__nav-bar-btn active-link' : 'btn__nav-bar-btn'}`} onClick={buttonWasClicked("cv")}>CV</button
></a></li></Link>
<Link to ='/about'><li><a data-page="about" className="about-link">
<button className={` ${isActive === "about" ? 'btn__nav-basr-btn active-link' : 'btn__nav-bar-btn'}`} onClick={buttonWasClicked("about")}>About</button>
</a></li></Link>
<Link to ='/contact'><li><a data-page="contact" className="contact-link">
<button className={` ${isActive === "contact" ? 'btn__nav-bar-btn active-link' : 'btn__nav-bar-btn'}`} onClick={buttonWasClicked("contact")}>Contact</button>
</a></li></Link>
</ul>
</nav>
);
}
export default NavBar;
ButtonClick.js (method to update the current page):
import NavBar from './Nav-bar';
function ChangeActiveButton(selectedButton) {
alert(selectedButton)
NavBar.isActive = toString(selectedButton);
}
export default ChangeActiveButton;