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

準備

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

JavaScript

ベースの ListGroup.js です。

import React, { ComponentProps, forwardRef } from 'react';
import {
  ListGroup as FlowbiteListGroup,
} from 'flowbite-react';
import { LegacyRef } from 'react';

const ListGroup = forwardRef((
  {
    children,
    ...otherProps
  },
  ref,
) => {
  return (
    <FlowbiteListGroup
      ref={ref}
      {...otherProps}
    >
      {children}
    </FlowbiteListGroup>
  );
});

const ListGroupItem = forwardRef((
  {
    active = false,
    children,
    disabled = false,
    href,
    icon,
    onClick,
    ...otherProps
  },
  ref,
) => {
  return (
    <FlowbiteListGroup.Item
      active={active}
      disabled={disabled}
      href={href}
      icon={icon}
      onClick={onClick}
      ref={ref}
      {...otherProps}
    >
      {children}
    </FlowbiteListGroup.Item>
  );
});

export default Object.assign(ListGroup, {
  Item: ListGroupItem,
});

TypeScript

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

import React, { ComponentProps, forwardRef } from 'react';
import {
  ListGroup as FlowbiteListGroup,
  ListGroupProps as FlowbiteListGroupProps,
} from 'flowbite-react';
import { LegacyRef } from 'react';

type ListGroupProps = {} & FlowbiteListGroupProps;

const ListGroup = forwardRef((
  {
    children,
    ...otherProps
  }: ListGroupProps,
  ref: LegacyRef<HTMLDivElement>,
) => {
  return (
    <FlowbiteListGroup
      ref={ref}
      {...otherProps}
    >
      {children}
    </FlowbiteListGroup>
  );
});

type ListGroupItemProps = {} & ComponentProps<typeof FlowbiteListGroup.Item>;

const ListGroupItem = forwardRef((
  {
    active = false,
    children,
    disabled = false,
    href,
    icon,
    onClick,
    ...otherProps
  }: ListGroupItemProps,
  ref: LegacyRef<HTMLAnchorElement>,
) => {
  return (
    <FlowbiteListGroup.Item
      active={active}
      disabled={disabled}
      href={href}
      icon={icon}
      onClick={onClick}
      ref={ref}
      {...otherProps}
    >
      {children}
    </FlowbiteListGroup.Item>
  );
});

export default Object.assign(ListGroup, {
  Item: ListGroupItem,
});

結果

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

はい、できました。