Home > Web Front-end > JS Tutorial > body text

How to create a custom table component with React and Typescript (Part 2)

Patricia Arquette
Release: 2024-10-09 18:25:02
Original
468 people have browsed it

Introduction

Yay! ? You've made it to the final part of this two-part series! If you haven't already checked out Part 1, stop right here and go through that first. Don't worry, we'll wait until you’re back! ?

In Part 1, we built the CustomTable component. You can see it in action here.

In this second part, we’ll be extending the component to add some new features. Here's what we'll be working towards:
How to create a custom table component with React and Typescript (Part 2)

To support this, the CustomTable component will need some enhancements:

  1. The ability to format the rendered value—e.g., rendering a number with proper formatting.
  2. Flexibility to allow users to provide custom templates for rendering rows, giving them control over how each column is displayed.

Let's dive into building the first feature.

Extending the Column Interface

We’ll start by adding a format method to the Column interface to control how specific columns render their values.

interface Column<T> {
  id: keyof T;
  label: string;
  format?: (value: string | number) => string;
}
Copy after login

This optional format method will be used to format data when necessary. Let’s see how this works with an example from the Country.tsx file. We’ll add a format method to the population column.

const columns: Column<Country>[] = [
  { id: "name", label: "Name" },
  { id: "code", label: "ISO\u00a0Code" },
  {
    id: "population",
    label: "Population",
    format: (value) => new Intl.NumberFormat("en-US").format(value as number),
  },
  {
    id: "size",
    label: "Size\u00a0(km\u00b2)",
  },
  {
    id: "density",
    label: "Density",
  },
];
Copy after login

Here, we’re using the JavaScript Intl.NumberFormat method to format the population as a number. You can learn more about this method here.

Next, we need to update our CustomTable component to check for the format function and apply it when it exists.

<TableBody>
  {rows.map((row, index) => (
    <TableRow hover tabIndex={-1} key={index}>
      {columns.map((column, index) => (
        <TableCell key={index}>
          {column.format
            ? column.format(row[column.id] as string)
            : (row[column.id] as string)}
        </TableCell>
      ))}
    </TableRow>
  ))}
</TableBody>
Copy after login

With this modification, the population column now renders with the appropriate formatting. You can see it in action here.

Supporting Custom Templates

Now, let's implement the next feature: allowing custom templates for rendering columns. To do this, we’ll add support for passing JSX as a children prop or using render props, giving consumers full control over how each cell is rendered.

First, we’ll extend the Props interface to include an optional children prop.

interface Props<T> {
  rows: T[];
  columns: Column<T>[];
  children?: (row: T, column: Column<T>) => React.ReactNode;
}
Copy after login

Next, we’ll modify our CustomTable component to support this new prop while preserving the existing behavior.

<TableRow>
  {columns.map((column, index) => (
    <TableCell key={index}>
      {children
        ? children(row, column)
        : column.format
        ? column.format(row[column.id] as string)
        : row[column.id]}
    </TableCell>
  ))}
</TableRow>
Copy after login

This ensures that if the children prop is passed, the custom template is used; otherwise, we fall back to the default behavior.

Let’s also refactor the code to make it more reusable:

const getFormattedValue = (column, row) => {
  const value = row[column.id];
  return column.format ? column.format(value) : value as string;
};

const getRowTemplate = (row, column, children) => {
  return children ? children(row, column) : getFormattedValue(column, row);
};
Copy after login

Custom Row Component

Now let’s build a custom row component in the Countries.tsx file. We’ll create a CustomRow component to handle special rendering logic.

interface RowProps {
  row: Country;
  column: Column<Country>;
}

const CustomRow = ({ row, column }: RowProps) => {
  const value = row[column.id];
  if (column.format) {
    return <span>{column.format(value as string)}</span>;
  }
  return <span>{value}</span>;
};
Copy after login

Then, we’ll update Countries.tsx to pass this CustomRow component to CustomTable.

const Countries = () => (
  <CustomTable columns={columns} rows={rows}>
    {(row, column) => <CustomRow column={column} row={row} />}
  </CustomTable>
);
Copy after login

For People.tsx, which doesn’t need any special templates, we can simply render the table without the children prop.

const People = () => <CustomTable columns={columns} rows={rows} />;
Copy after login

Improvements

One improvement we can make is the use of array indexes as keys, which can cause issues. Instead, let’s enforce the use of a unique rowKey for each row.

We’ll extend the Props interface to require a rowKey.

interface Props<T> {
  rowKey: keyof T;
  rows: T[];
  columns: Column<T>[];
  children?: (row: T, column: Column<T>) => React.JSX.Element | string;
  onRowClick?: (row: T) => void;
}
Copy after login

Now, each consumer of CustomTable must provide a rowKey to ensure stable rendering.

<CustomTable
  rowKey="code"
  rows={rows}
  onRowClick={handleRowClick}
  columns={columns}
>
  {(row, column) => <CustomRow column={column} row={row} />}
</CustomTable>
Copy after login

Final Code

Check out the full code here.

Conclusion

In this article, we extended our custom CustomTable component by adding formatting options and the ability to pass custom templates for columns. These features give us greater control over how data is rendered in tables, while also making the component flexible and reusable for different use cases.

We also improved the component by enforcing a rowKey prop to avoid using array indexes as keys, ensuring more efficient and stable rendering.

I hope you found this guide helpful! Feel free to share your thoughts in the comments section.

Thanks for sticking with me through this journey! ?

The above is the detailed content of How to create a custom table component with React and Typescript (Part 2). For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template