I am creating a dynamic menu from an array but I only want an onClick method on the last item.This is in a ReactJS component. In the dropDownMenu.map, how do I setup the anchor tag to only have an onClick as defined in the array?
const dropDownMenu = [
{ name: 'Profile', href: '#' },
{ name: 'Settings', href: '#' },
{ name: 'Sign out', href: '#', onClick=logOut }
];
const logout = () => {
signOut();
};
{dropDownMenu.map((item) => (
<Menu.Item key={item.name}>
{({ active }) => (
<a href={item.href}>
{item.name}
</a>
)}
</Menu.Item>
))}
>Solution :
You don’t need to check anything in onClick it’s an extra useless code react handle this implicitly if the clickHandler is undefined. this link may help you.
const logout = () => {
signOut();
};
const dropDownMenu = [
{ name: "Profile", href: "#" },
{ name: "Settings", href: "#" },
{ name: "Sign out", href: "#", clickHandler: logOut },
];
{
dropDownMenu.map((item) => (
<Menu.Item key={item.name}>
{({ active }) => <a onClick={item.clickHandler} href={item.href}>{item.name}</a>}
</Menu.Item>
));
}