Today I Learned

TIL, 2024-02-27

React component as prop: the right way™️

Reference

  • Ideal: “Give me an icon, I don’t care which one, your choice, and I’ll render it in the right place.”
  • Pass component as element?
type ButtonProps = {
  children: ReactNode;
  icon: ReactElement<IconProps>;
};
  • Pass as component itself? ``` type ButtonProps = { children: ReactNode; Icon: ComponentType; };

export const ButtonWithIconComponent = ({ children, Icon, }: ButtonProps) => { return ( ); };


- Pass as function?

type ButtonProps = { children: ReactNode; renderIcon: () => ReactElement; };

export const ButtonWithIconRenderFunc = ({ children, renderIcon, }: ButtonProps) => { // getting the Element from the function const icon = renderIcon(); return ( ); }; ```

Having default values for some props of the passed-in Icon

  • React Element - you have to do cloneElement.

This project is maintained by daryllxd