简体   繁体   中英

How can i make an icon dynamic with react typescript?

sorry but I just started using react and typescript, I need the icon to change according to the status in the AppointmentType the body color works but the icons don't, can someone show me how to solve the problem?

const MapIcon: { [key in AppointmentType]?: React.FC<IIcon> } = {
          Videocall: Camera,
          Expired: Blocked,
          Confirmed: CheckInCircle,
          New: Hourglass,
          Past: CheckInCircle,
        };

        interface IconProps {
          iconType?: React.FC<IIcon>;
          color: string;
        }
        const IconCustom = (props: IconProps) => {
          const { iconType } = props;
          return <div>{iconType}</div>;
        };

        export const AppointmentCard: React.FC<IAppointmentCard> = ({
          name,
          hourLabel,
          type,
          isBonus,
          isModify,
          wasMade,
        }) => {
          const { t } = useTranslation();
          return (
            <Wrapper type={type}>
              <WrapperConfirmsAppointment>
                <IconCustom
                  iconType={MapIcon[type]}
                  color={dateLabelColors[type] || Theme.colors.candy[500]}
                />
                <Body
                  variant={TypographyVariant.SemiBold}
                  size={BodySize.Body60}
                  margin="0 0 0 6px"
                  color={dateLabelColors[type] || Theme.colors.candy[500]}
                >
                  {t('appointment.appointmentProposal.confirmed')}
                </Body>
              </WrapperConfirmsAppointment>
            </Wrapper>
          );
        };

I believe the problem here is that the IconCustom component just renders the value of the MapIcon object instead of an actual icon. In order to solve it you need to render the icon itself.

There a couple of ways to tackle that:

  1. You can alter the MapIcon structure to return the rendered icon (assuming that the values are the icons):
const MapIcon: { [key in AppointmentType]?: React.FC } = {
  Videocall: <Camera />, 
  Expired: <Blocked />
  ....
};
  1. Render the returned value as icons:
const IconCustom = (props: IconProps) => {
  const { iconType: IconType } = props;
  return <div><IconType /></div>;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM