I'm trying to add and remove a class when clicking on an item of my header, but I struggle to do it and I don't know how to map the rendered items in the header component.
Here's the first part of the code with a function that works for routing and window.location.
I'm able to add the class but it gets added to each element clicked and it gets removed only when I click again on it.
import React, { useState } from 'react';
const Link = ({ href, children }) => {
const [activeItem, setActiveItem] = useState(false);
const onClick = (event) => {
if (event.metaKey || event.ctrl) {
return;
}
event.preventDefault();
window.history.pushState({}, '', href);
const navEvent = new PopStateEvent('popstate');
window.dispatchEvent(navEvent);
setActiveItem(!activeItem);
};
return (
<a
onClick={onClick}
className={`item ${activeItem ? 'active' : ''}`}
href={href}
>
{children}
</a>
);
};
export default Link;
Here's my header element instead:
import React from 'react';
import Link from './Link';
import Logo from './Logo';
const Header = () => {
return (
<div className="ui secondary pointing menu">
<Link href="/">
<Logo />
</Link>
<div className="pointing right menu">
<Link href="/services">services</Link>
<Link href="/works">works</Link>
<Link href="/contacts">contacts</Link>
</div>
</div>
);
};
export default Header;
You need to make your link components aware of each other by lifting the state to your header component. Then you pass you tell your link components which link is currently selected by passing it as a prop and you also need to give them the ability to change which link is currently selected:
import React from 'react';
import Link from './Link';
import Logo from './Logo';
const Link = ({ href, children, isActive, handleClick }) => {
const onClick = (event) => {
if (event.metaKey || event.ctrl) {
return;
}
event.preventDefault();
window.history.pushState({}, '', href);
const navEvent = new PopStateEvent('popstate');
window.dispatchEvent(navEvent);
handleClick();
};
return (
<a
onClick={onClick}
className={`item ${isActive ? 'active' : ''}`}
href={href}
>
{children}
</a>
);
};
export default Link;
const Header = () => {
const [activeLink, setActiveLink] = useState(0)
return (
<div className="ui secondary pointing menu">
<Link
href="/"
isActive={activeLink === 0}
handleClick={() => setActiveLink(0)}
>
<Logo />
</Link>
<div className="pointing right menu">
<Link
href="/services"
isActive={activeLink === 1}
handleClick={() => setActiveLink(1)}
>
services
</Link>
<Link
href="/works"
isActive={activeLink === 2}
handleClick={() => setActiveLink(2)}
>
works
</Link>
<Link
href="/contacts"
isActive={activeLink === 3}
handleClick={() => setActiveLink(3)}
>
contacts
</Link>
</div>
</div>
);
};
export default Header;