0

To build a navigation menu I want to sender a set of MenuItemComponents that have label and icon I want to import those icons from an external library and then pass them as a propery of an object (that come from external library). This is the interface for that item

export interface MenuItem {
  id: number
  name: string
  icon?: ReactNode,
  path: string,
}

On the page I want to map this array with labels and icons.

{
   headerMenuItems.map((item: MenuItem) => (
     <MenuItemComponent item={item}/>
   ))
}

And here's my <MenuItemComponent />

import React from "react"
import { MenuItem } from "./items"


export interface MenuItemProps {
  item: MenuItem
}

export const MenuItemComponent = ({item}: MenuItemProps) => {
  const Icon = () => <>{item.icon}</>

  return (
    <a href={item.path}>
      <div>
        <Icon />
        <div>{item.name}</div>
      </div>
    </a>
  )
}

But I'm getting an error

Objects are not valid as a React child (found: object with keys {$$typeof, render}). If you meant to render a collection of children, use an array instead. in Icon (at MenuItem.tsx:14)

How can I get the desired result?

And a link to CodeSandbox Edit frosty-curie-fblm8

1 Answer 1

1

You have invalid values for MenuItem. icon is component not node.

You could change it like this Demo

export interface MenuItem {
  id: number
  name: string
  icon?: React.FC,
  path: string,
}

And then

export const MenuItemComponent = ({ item }: MenuItemProps) => {
  const { icon: Icon } = item;

  return (
    <a href={item.path}>
      <div>
        {Icon && <Icon />}
        <div>{item.name}</div>
      </div>
    </a>
  );
};
Sign up to request clarification or add additional context in comments.

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.