PackRat icon indicating copy to clipboard operation
PackRat copied to clipboard

Add a reusable Icon component in our ui package

Open Tadjaur opened this issue 10 months ago • 2 comments

@andrew-bierman: we should probably have a reusable Icon component in our ui package, that can be typesafe and use either expo vector icons, or the tamagui icons more easily. Ideally we can drop some of the expo icons as they bloat the bundle a good bit.

Tadjaur avatar Apr 13 '24 03:04 Tadjaur

I have a rough draft on a component for this

andrew-bierman avatar Apr 13 '24 13:04 andrew-bierman

Maybe something like this?

import React from 'react';
import * as ExpoIcons from '@expo/vector-icons';
import * as TamaguiIcons from '@tamagui/lucide-icons';

export type IconSource = 'expo' | 'tamagui';

export type ExpoIconProvider = keyof typeof ExpoIcons;

export type TamaguiIconName = keyof typeof TamaguiIcons;
export type ExpoIconName = IconProps<'expo', ExpoIconProvider>['name'];

export type IconProps<T extends IconSource, P extends ExpoIconProvider> = T extends 'expo'
  ? React.ComponentProps<(typeof ExpoIcons)[P]>
  : T extends 'tamagui'
    ? React.ComponentProps<(typeof TamaguiIcons)[keyof typeof TamaguiIcons]>
    : never;

export interface Props<T extends IconSource, P extends ExpoIconProvider> {
  source?: T;
  provider?: P;
  name: T extends 'expo' ? IconProps<T, P>['name'] : keyof typeof TamaguiIcons;
  size?: number;
  color?: string;
  [key: string]: any;
}

export const Icon = <
  T extends IconSource = 'expo',
  P extends ExpoIconProvider = 'MaterialCommunityIcons',
>({
  source = 'expo' as T,
  provider = 'FontAwesome' as P,
  name,
  size = 24,
  color,
  ...props
}: Props<T, P>) => {
  let IconComponent: React.ComponentType<any> | undefined;

  switch (source) {
    case 'expo':
      IconComponent = ExpoIcons[provider];
      break;
    case 'tamagui':
      IconComponent = TamaguiIcons[name as keyof typeof TamaguiIcons];
      break;
    default:
      console.warn(`Unsupported icon source: ${source}`);
  }

  if (!IconComponent) {
    console.warn(
      `Icon '${name}' not found in the specified source '${source}' and provider '${provider}'.`,
    );
    return null;
  }

  return <IconComponent name={name} size={size} color={color} {...props} />;
};

andrew-bierman avatar May 09 '24 13:05 andrew-bierman