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

準備

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

JavaScript

ベースの Accordion.js です。

import { forwardRef } from 'react';
import { Accordion as FlowbiteAccordion } from 'flowbite-react';

const Accordion = forwardRef((
  {
    alwaysOpen = false,
    children,
    panels = [],
    flush = true,
    ...otherProps
  },
  ref,
) => {
  return (
    <FlowbiteAccordion
      alwaysOpen={alwaysOpen}
      flush={flush}
      ref={ref}
      {...otherProps}
    >
      {
        panels.map(panel => (
          <FlowbiteAccordion.Panel key={panel.id}>
            <FlowbiteAccordion.Title>
              {panel.title}
            </FlowbiteAccordion.Title>
            <FlowbiteAccordion.Content>
              {panel.content}
            </FlowbiteAccordion.Content>
          </FlowbiteAccordion.Panel>
        ))
      }
    </FlowbiteAccordion>
  );
});

export default Accordion;

TypeScript

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

import { forwardRef } from 'react';
import {
  Accordion as FlowbiteAccordion,
  AccordionProps as FlowbiteAccordionProps,
} from 'flowbite-react';

type AccordionProps = {
  panels: { id: string, title: React.ReactNode, content: React.ReactNode }[];
} & FlowbiteAccordionProps;

const Accordion = forwardRef((
  {
    alwaysOpen = false,
    children,
    panels = [],
    flush = true,
    ...otherProps
  }: AccordionProps,
  ref: LegacyRef<HTMLDivElement>,
) => {
  return (
    <FlowbiteAccordion
      alwaysOpen={alwaysOpen}
      flush={flush}
      ref={ref}
      {...otherProps}
    >
      {
        panels.map(panel => (
          <FlowbiteAccordion.Panel key={panel.id}>
            <FlowbiteAccordion.Title>
              {panel.title}
            </FlowbiteAccordion.Title>
            <FlowbiteAccordion.Content>
              {panel.content}
            </FlowbiteAccordion.Content>
          </FlowbiteAccordion.Panel>
        ))
      }
    </FlowbiteAccordion>
  );
})

export default Accordion;

結果

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

はい、できました。