How to pass in a React icon as a prop and style it with Tailwind

Hello I'm trying to create a reusable react component that takes in an icon and I want to style said icon with a base style. I included some screenshots of what I have so far. I've been at this for a while, any help would be very much appreciated.
10 Replies
Lukem121
Lukem1213y ago
Set the type as React.ReactNode You could also use JSX.Element or React Element
benten
benten3y ago
I believe React.ReactNode is the most permissive
LUNA
LUNAOP3y ago
I get the same type error in both
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Finn
Finn3y ago
Does the type     HTMLProps<HTMLButtonElement> work? Ovs with htmlsvg element or whatever it is Wait no ignore me 🤦‍♂️
Lukem121
Lukem1213y ago
import { HomeIcon } from "@heroicons/react/20/solid"; interface IButtonProps { Icon: React.ReactNode; } const Button = ({ Icon }: IButtonProps) => { return <>{Icon} Click me!</>; }; export default function Test() { return ( <> <Button Icon={<HomeIcon className="text-lime-500" />} /> </> ); }
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
LUNA
LUNAOP3y ago
I got it working by this thank you guys so much, I did a mix of everything you guys said. Thx everyone 😁😁
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
bennettdev
bennettdev3y ago
There's something additionally needed for a type-safe usage. You can give the icon props as a generic, but then you need to make TypeScript happy by also checking whether this is a valid React element:
function Button(props: Props) {
return (
<button onClick={props.onClick}>
{React.isValidElement<Props['icon']>(props.icon) ? (
React.cloneElement<Props['icon']>(props.icon, {
className: 'text-current',
})
) : (
<></>
)}
</button>
)
}
function Button(props: Props) {
return (
<button onClick={props.onClick}>
{React.isValidElement<Props['icon']>(props.icon) ? (
React.cloneElement<Props['icon']>(props.icon, {
className: 'text-current',
})
) : (
<></>
)}
</button>
)
}
Want results from more Discord servers?
Add your server