Search code examples
javascriptreactjstypescriptnext.jsreact-props

Pass array as prop in React Typescript


I've Navbar component inside which I'm creating a NavDropdown component to use inside the Navbar. I want to pass array as prop to the NavDropdown component to display its dropdown items. The array will be of structure:

DropDownItems: [
        {
          title: "Keywords",
          to: "/app/keywords",
        },
        {
          title: "Followers",
          to: "/app/followers",
        },
        {
          title: "Following",
          to: "/app/following",
        },
      ]

However, I'm getting the following 2 errors:

  1. Property 'map' does not exist on type 'SubItemsProps'.
  2. Parameter 'subItem' implicitly has an 'any' type.

Navbar.tsx


    type SubItemsProps = {
              subItems: DropdownItem[]
            }
        
        interface DropdownItem {
          subTitle: string,
          subLink: string
        }
        const NavDropdown = ({
                title,
                subItems
              }: {
                title: string;
                subItems: SubItemsProps;
              }) => {
                return (
                  <div>
                    <div>{title}</div>
                    <div>
                      <ul>
                        {subItems.map(subItem => (
                          <Link href={subItem.subLink}>
                            <li>
                              <span>
                                {subItem.subTitle}
                              </span>
                            </li>
                          </Link>
                        ))}
                      </ul>
                    </div>
                  </div>
                );
              };


/* Navbar component */


Solution

  • just edit:

    type SubItemsProps = DropdownItem[]