[React+Tailwind] Alert を TypeScript に書き直してみた | 心を無にして始める React

2022-09-12

準備

書き直すベースはこちらの Alert コンポーネントです。

JavaScript

ベースの Alert.js です。

import { forwardRef } from 'react';
import { Alert as FlowbiteAlert } from 'flowbite-react';

const Alert = forwardRef(({
  show,
  additionalContent,
  children,
  color = "success",
  icon,
  onDismiss,
  rounded = true,
  withBorderAccent = true,
  ...otherProps
}, ref) => {

  if (!show) {
    return <></>;
  }

  return (
    <FlowbiteAlert
      additionalContent={additionalContent}
      color={color}
      icon={icon}
      onDismiss={onDismiss}
      ref={ref}
      rounded={rounded}
      withBorderAccent={withBorderAccent}
      {...otherProps}
    >
      {children}
    </FlowbiteAlert>
  );
})

export default Alert;

TypeScript

Alert.tsx として編集します。

import { forwardRef, LegacyRef } from 'react';
import {
  Alert as FlowbiteAlert,
  AlertProps as FlowbiteAlertProps,
} from 'flowbite-react';

type AlertProps = {
  show: boolean,
} & FlowbiteAlertProps;

const Alert = forwardRef((
  {
    show,
    additionalContent,
    children,
    color = "success",
    icon,
    onDismiss,
    ref={ref}
    rounded = true,
    withBorderAccent = true,
    ...otherProps
  }: AlertProps,
  ref: LegacyRef<HTMLDivElement>,
) => {

  if (!show) {
    return <></>;
  }

  return (
    <FlowbiteAlert
      additionalContent={additionalContent}
      color={color}
      icon={icon}
      onDismiss={onDismiss}
      rounded={rounded}
      withBorderAccent={withBorderAccent}
      {...otherProps}
    >
      {children}
    </FlowbiteAlert>
  );
})

export default Alert;

結果

変化はないので、前と同じ。

はい、できました。