Data rerenders only once onClick using function with filter() in reactjs?
I have a navigation bar with 3 buttons (not the main navbar) that should filter menu items onto Pizzas, Sides, Drinks when clicked. When I click either button it only shows one of the filtered menu (if I click Pizzas, it shows the list of different pizzas).
The issue is that it only works once, so if I click again or click Sides or Drinks, it doesn't show anything, just an empty page. I thought about using useEffect to re-render, but can't think of a way on how to use it.
How can I make each button show the different data/menu items when clicking each menu category (Pizzas, Sides, Drinks)?
const Menu = () => {
const [menuList, setMenuList] = useState(initialMenuList);
function eventMenuClick(e) {
const nameSelection = e.currentTarget.textContent;
setMenuList((menuList) => {
return menuList.filter((item) => {
if (item.category === nameSelection) {
return console.log(item);
}
return null;
});
});
}
return (
<div className="container">
<h1>Menu</h1>
<div className="nav-container">
<ul className="menu-list">
<li className="menutype" onClick={eventMenuClick}>Pizzas</li>
<li className="menutype" onClick={eventMenuClick}>Sides</li>
<li className="menutype" onClick={eventMenuClick}>Drinks</li>
</ul>
</div>
<MenuList menuList={menuList} />
<NavBar />
</div>
);
};
export default Menu;
const MenuList = ({ menuList }) => {
return (
<div className="menulist-container">
{menuList.map((item) => (
<MenuItem
key={item.id}
title={item.name}
image={item.image}
price1={item.priceM}
price2={item.priceL}
/>
))}
</div>
);
};
export default MenuList;
In your menu, you can have another state which contains only filtered values.
const [menuList, setMenuList] = useState(initialMenuList);
const [visibleMenu, setVisibleMenu] = useState(initialMenuList); // <- HERE
function eventMenuClick(e) {
const nameSelection = e.currentTarget.textContent;
const filtered = menuList.filter((item) => item.category === nameSelection);
setVisibleMenu(filtered);
}
And when you render your list, instead of original data, use filtered to be rendered.
<MenuList menuList={visibleMenu} />