I have an array of objects that contain keypair values for the navbar links, I have mapped the array to list and rendering it successful, but when I try to add class to only act
Instead of trying to manipulate the DOM manually, you could keep a piece of state called e.g. activeLink
that stores the id of the active link that you use that to apply the class to the active link in the render method.
Example
class SideNavbar extends React.Component {
state = {
links: [
{
id: 1,
name: "Link1",
to: "/cms",
className: "side_nav_item"
},
{
id: 2,
name: "Link2",
to: "/cms",
className: "side_nav_item"
},
{
id: 3,
name: "Link3",
to: "/cms",
className: "side_nav_item"
},
{
id: 4,
name: "Link4",
to: "/cms",
className: "side_nav_item"
}
],
activeLink: null
};
handleClick = id => {
this.setState({ activeLink: id });
};
render() {
const { links, activeLink } = this.state;
return (
{links.map(link => {
return (
- this.handleClick(link.id)}
className={
link.className +
(link.id === activeLink ? " active_item" : "")
}
>
{link.name} {link.id === activeLink && "active!"}
);
})}
);
}
}
ReactDOM.render( , document.getElementById("root"));