Simon
Simon

Reputation: 10150

ReactJS add component to Javascript object

I'm using a Javascript object to hold the info for a side menu (e.g. name, path), then using a couple of nested maps to build the actual menu composed of MUI components. This works for info that is stored as JS primitive types, but I also want to include an icon as part of that object, which itself is a React component coming from MUI. Example:

  const menuItems = {
    Text: [
      { name: 'TTS', path: 'textTTS', icon: </InboxIcon>, enabled: true },
    ],
    Image: [...],
    Video: [...],
    Live: [...],
  }

However, I get an error because (I think) it's trying to evaluate the actual component when I add it to the object:

Unexpected token (26:45)

  24 |   const menuItems = {
  25 |     Text: [
> 26 |       { name: 'TTS', path: 'textTTS', icon: </InboxIcon>, enabled: true },
     |                                              ^
  27 |     ],

What's the correct way to reference a component, without actually adding the contents of the component to an object?

FYI here is how I'm building the actual side menu:

let menuComponents = Object.keys(menuItems).map((header, index) => {
    return (
      <List
        key={header}
        subheader={
          <ListSubheader component="div" id="nested-list-subheader">
            {header}
          </ListSubheader>
        }
      >
        {menuItems[header].map((item, index) => {
          return (
            <ListItem
              key={item.path}
              disablePadding
              sx={{ display: 'block' }}
              onClick={() => {
                navigate(item.path);
              }}
            >
              <ListItemButton disabled={item.enabled ? false : true}>
                <ListItemIcon>{item.icon}</ListItemIcon>
                <ListItemText primary={item.name} />
              </ListItemButton>
            </ListItem>
          );
        })}
      </List>
    );
  });

Upvotes: 2

Views: 387

Answers (1)

Paulo
Paulo

Reputation: 1498

Did you mean <InboxIcon />? Since I cannot see where you opened it, so I believe that's the problem.

Upvotes: 1

Related Questions