ManavM
ManavM

Reputation: 3098

How to pass props to component passed to MenuItem in material-ui

I have the following code to render a notification menu

      <Menu
        anchorEl={notificationAnchorEl}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
        transformOrigin={{ vertical: 'top', horizontal: 'right' }}
        open={isNotificationMenuOpen}
        onClose={this.handleNotificationMenuClose}
      >
        {notifications.map(notification => (
          <MenuItem
            key={notification.id}
            component={NotificationItem}
            onClick={this.handleNotificationMenuClose}
          />
        ))}
      </Menu>

What I don't understand is how do I pass props to the NotificationItem Component using the notification object I have.

Upvotes: 1

Views: 4204

Answers (2)

ManavM
ManavM

Reputation: 3098

After some research I found the answer in the implementation of the ListItem Component.

Turns out that all the additional props given to ListItem are passed on the to component.

const {
  component: componentProp,
  ...other
} = props;

const componentProps = { className, disabled, ...other };
let Component = componentProp || 'li';

return (
  <ContainerComponent
    className={classNames(classes.container, ContainerClassName)}
    {...ContainerProps}
  >
    <Component {...componentProps}>{children}</Component>
    {children.pop()}
  </ContainerComponent>
);

^ relevant code from ListItem.js

So the following code will work

 {notifications.map(notification => (
   <MenuItem
     component={NotificationItem}
     onClick={this.handleNotificationMenuClose}
     notification={notification}
   />
  ))}

Upvotes: 1

darksmurf
darksmurf

Reputation: 3967

Just render a NotificationItem inside the MenuItem if that is what you want.

Also, remember to pass a unique key prop to each element mapped from an array.

<Menu
    anchorEl={notificationAnchorEl}
    anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
    transformOrigin={{ vertical: 'top', horizontal: 'right' }}
    open={isNotificationMenuOpen}
    onClose={this.handleNotificationMenuClose}
>
    {notifications.map((notification, i) => (
        <MenuItem
           key={i}
           onClick={this.handleNotificationMenuClose}
        >
            <NotificationItem someProp={notification.someProp}/>
        </MenuItem>
    ))}
</Menu>

Upvotes: 1

Related Questions