0

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>
))}
0

3 Answers 3

1

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>
  ));
}
Sign up to request clarification or add additional context in comments.

Comments

0

Array.prototype.map has a second parameter in it's callback function, you can check to see if it is the last value in the array, and if it is, you can pass the callback

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

const dropDownMenu = [
    { name: 'Profile', href: '#' },
    { name: 'Settings', href: '#' },
    { name: 'Sign out', href: '#' }
];

const logout = () => {
    signOut();
};

{
    dropDownMenu.map((item, index) => (
        <Menu.Item key={item.name}>
            {({ active }) => (
                <a href={item.href} onClick={dropDownMenu.length - 1 === index ? logout : null}>
                    {item.name}
                </a>
            )}
        </Menu.Item>
    ))
}

Comments

0

onClick and href props are available in an anchor tag, you can directly pass using destructuring.

const dropDownMenu = [
    { name: 'Profile', href: '#' },
    { name: 'Settings', href: '#' },
    { name: 'Sign out', href: '#', onClick:logOut }
];

const logout = () => {
  signOut();
};

{dropDownMenu.map(({name, ...rest}) => (
  <Menu.Item key={name}>{({ active }) => (<a {...rest}>{name}</a>)}</Menu.Item>
))}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.