Home > Net >  How to pass icons as props in react with typescript
How to pass icons as props in react with typescript

Time:09-30

I am new to typescript and started a simple project. I have a sidebar component that is made up of several sidebarNavigationItem components. Each Sidebar item has an Icon and Title, as shown below.

Sidebar.tsx

import SidevarNavigationItem from "./SidevarNavigationItem"
import { HomeIcon } from "@heroicons/react/24/solid"
import { StarIcon } from "@heroicons/react/24/solid"


const Sidebar = () => {
  return (
    <nav
      id="sidebar"
      className="p-2 mt-5 max-w-2xl xl:min-w-fit sticky top-20 flex-grow-0.2 text-center h-screen"
    >
      <div id="navigation">
        <SidevarNavigationItem Icon={<HomeIcon />} name="Homepage" source="/" />
        <SidevarNavigationItem
          Icon={<StarIcon />}
          name="Tournaments"
          source="/tournaments"
        />
       
      </div>
    </nav>
  )
}

export default Sidebar

SidebarNavigationItem.tsx

import Link from "next/link"
import { FunctionComponent } from "react"

interface Props {
  Icon: React.ElementType
  name: string
  source: string
}

const SidevarNavigationItem: FunctionComponent<Props> = ({
  Icon,
  name,
  source,
}) => {
  return (
    <Link href={source}>
      <div className="flex items-center cursor-pointer text-3xl space-x-5 justify-center">
        {Icon && <Icon classname="h-8 w-8 text-red-500" />}
        <p className="hidden sm:inline-flex font-medium">{name}</p>
      </div>
    </Link>
  )
}

export default SidevarNavigationItem

The issue is that I can't style the icons that have been passed down as props when the type is JSX.Element. Changing the type of the Icon to React.ElementType will let me add styles but causes an error in the parent that says

Type 'Element' is not assignable to type 'ElementType'

What do I do?

CodePudding user response:

You need to pass the component reference itself instead of its rendered jsx.

So, in your Sidebar.tsx component, you need to replace these lines:

Icon={<HomeIcon />}
Icon={<StarIcon />}

with these lines respectively:

Icon={HomeIcon}
Icon={StarIcon}

The final code should be like this:

<div id="navigation">
    <SidevarNavigationItem Icon={HomeIcon} name="Homepage" source="/" />
    <SidevarNavigationItem
      Icon={StarIcon}
      name="Tournaments"
      source="/tournaments"
    />
</div>
  • Related