reactjsmenuantd

Error with React Menu - Expected an assignment or function call and instead saw an expression


I'm new to React so bear with me.

I'm trying to build out a side menu navigation. This is the beginning of the application so I will be adding more nav titles in the future. To future proof, I'm trying to store the key/labels for the item tags in an array. Within React render, I'm trying to iterate over the array and insert the key/label accordingly. However, I'm running into the below error. Line 41 corresponds to key: menuItem["key"];.

Why do I see this error and how do I fix it?

Line 41:11: Expected an assignment or function call and instead saw an expression

import '../../src/index.css';
import { UploadOutlined, UserOutlined, VideoCameraOutlined } from '@ant-design/icons';
import { Layout, Menu, theme } from 'antd';

const { Header, Content, Footer, Sider } = Layout;

const App: React.FC = () => {
  const {
    token: { colorBgContainer },
  } = theme.useToken();
  const menuItems = [
      {
          key: "nav1",
          label: "Nav 1"
      },
      {
          key: "nav2",
          label: "Nav 2"
      }
  ]


  return (
    <Layout>
      <Sider
        breakpoint="lg"
        collapsedWidth="0"
        onBreakpoint={(broken) => {
          console.log(broken);
        }}
        onCollapse={(collapsed, type) => {
          console.log(collapsed, type);
        }}
      >
        <div className="logo" />
        <Menu
          theme="dark"
          mode="inline"
          items={menuItems.forEach((menuItem) => {
              key: menuItem["key"];
              label: menuItem["label"];
              })
          }
        />
      </Sider>
    </Layout>
  );
};

export default App;

Solution

  • There are two things wrong with your code.

    The first is the syntax error that is caused by { } in JavaScript being both the function body syntax and object syntax.

    In the context of an arrow function () => {} the { } means you are opening up the body of the function. This means you have to return from the body instead of it being implicit (no function body).

    To correct this, you can simply wrap the function body in parenthesis so that it treats it as an implicit return, and treats the { } as an object instead:

    (menuItem) => ({
      key: menuItem["key"];
      label: menuItem["label"];
    })
    

    The second problem is that forEach does not accept a return value. You need to use map.

    items={menuItems.map((menuItem) => ({
      key: menuItem["key"];
      label: menuItem["label"];
    }))}
    

    Note

    Unless your code is simplified for the question's sake, your loop is completely unnecessary. You are mapping the objects into new objects that have the same values.

    If this is truly the case, you can remove this completely from your code and just do items={menuItems}.