user16949958
user16949958

Reputation:

How to pass an icon as a prop?

I'm using props and I want to have "optionText" and "optionIcon" the 1st one I'm able to add but I'm not able to implement an icon as a prop

File where I'm creating props

import Icon from "@mui/material/Icon";

function HeaderMenuOptions({ optionText, OptionIcon }) {
  return (
    <div className="flex items-center text-center">
      <Icon>{OptionIcon}</Icon>
      <h1 className="py-1 my-1 hover:bg-menu-option-hover hover:text-black cursor-pointer">
        {optionText}
      </h1>
    </div>
  );
}

export default HeaderMenuOptions;

file where I'm using said props

        <div className="absolute left-72 top-3 rounded-md bg-section w-[10rem] text-center">
          <p className="menu-header mt-2">VIEW OPTIONS</p>

          <div className="flex items-center justify-center space-x-2 mr-2 cursor-pointer hover:bg-menu-option-hover hover:hover:text-black group">
            <HeaderMenuOptions optionText="Night Mode" />
            <CheckBoxIcon
              defaultChecked
              onClick={() => alert("Light mode has not been added yet!")}
              className="cursor-pointer text-blue-500"
            />
          </div>

          <p className="menu-header">MORE STUFF</p>
          <HeaderMenuOptions optionText="Premium" OptionIcon={SecurityIcon} />
          <HeaderMenuOptions optionText="TEST" />
          <HeaderMenuOptions optionText="TEST" />
          <HeaderMenuOptions optionText="TEST" />
          <HeaderMenuOptions optionText="TEST" />
        </div>

can anyone please help me. Thanks

Upvotes: 9

Views: 16043

Answers (3)

gfalco
gfalco

Reputation: 1

You can wrap the icon prop inside an object:

import { HomeIcon } from '@heroicons/react/24/outline';

function TargetComponent({ icon }){

    const iconObj = { icon };

    return <iconObj.icon />
}

function ParentComponent () {
    return <TargetComponent icon={ HomeIcon } />
}

Upvotes: 0

Alaa M
Alaa M

Reputation: 427

You can use pass icon as JSX.Element from ParentComponent to TargetComponent as the following:

import AddAlertIcon from '@mui/icons-material/AddAlert';
...

const ParentComponent=()=>{
return(
....
<TargetComponent icon={<AddAlertIcon />}>
....
)
}

const TargetComponent = (props: Props) => {
return(
<span>
{props.icon}
</span>
);
}

export type Props= {
  icon:  JSX.Element;
};

Upvotes: 2

Mehul Thakkar
Mehul Thakkar

Reputation: 2447

The HeaderMenuOptions looks fine. You need to change the parent component.

You can do something like this.

<HeaderMenuOptions optionText="Premium" OptionIcon={<SecurityIcon />} />

Upvotes: 13

Related Questions