I have a list and it's already set to Active, I mean the first list is already active, but my question is how to make the other list active also only when it's clicked and as long it's clicked and on the same page it keeps active.
return (
<div className="sidebar">
<div className="sidebarWrapper">
<div className="sidebarMenu">
<h3 className="sidebarTitle">Dashboard</h3>
<ul className="sidebarList">
<Link to="/" className="link">
<li className="sidebarListItem active">
<LineStyleIcon className="sidebarIcon" />
Home
</li>
</Link>
<li className="sidebarListItem">
<TimelineIcon className="sidebarIcon" />
Analytics
</li>
<li className="sidebarListItem">
<TrendingUpIcon className="sidebarIcon" />
Sales
</li>
</ul>
);
CSS:
.sidebarTitle {
font-size: 18px;
font-weight: 700;
color: rgb(187, 186, 186);
}
.sidebarList {
list-style: none;
padding: 5px;
}
.sidebarListItem.active,
.sidebarListItem:hover {
background-color: black;
color: white;
}
CodePudding user response:
I would store the list items in an array so that I can loop over them later
const listItems = ["Home", "Analytics", "Sales"];
and I would create a state to store the active index
const [activeIndex, setActiveIndex] = React.useState(0);
and finally I would render the list items like this:
<ul className="sidebarList">
{listItems.map((listItem, index) => {
return (
<li
onClick={() => setActiveIndex(index)}
className={`sidebarListItem ${
index === activeIndex ? "active" : ""
}`}
>
{listItem}
</li>
);
})}
</ul>
when the user clicks on the item .. the activeIndex will be set as the item-index for the clicked item ..
and I am adding the className: "active" to the list-item only when the item-index === activeIndex
CodePudding user response:
Your component will need to keep state for the currently active item. The initial state can be 0
, the index of the first element in the list of items. When another item is clicked, we can setActive(index)
for the index
of the clicked item. Determining an individual item's active
property is a derivative of the active
state and the item's index
, active == index
-
function App({ items = [] }) {
const [active, setActive] = React.useState(0)
return items.map((value, index) =>
<ListItem
key={index}
value={value}
active={index == active}
onClick={_ => setActive(index)}
/>
)
}
function ListItem({ value, active, onClick }) {
return <button
type="button"
class={active ? "active" : "inactive"}
onClick={onClick}
children={value}
/>
}
ReactDOM.render(<App items={["