"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to create a custom table component with React and Typescript (Part 2)

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

Published on 2024-11-08
Browse:239

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 {
  id: keyof T;
  label: string;
  format?: (value: string | number) => string;
}

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[] = [
  { 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",
  },
];

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.


  {rows.map((row, index) => (
    
      {columns.map((column, index) => (
        
          {column.format
            ? column.format(row[column.id] as string)
            : (row[column.id] as string)}
        
      ))}
    
  ))}

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 {
  rows: T[];
  columns: Column[];
  children?: (row: T, column: Column) => React.ReactNode;
}

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


  {columns.map((column, index) => (
    
      {children
        ? children(row, column)
        : column.format
        ? column.format(row[column.id] as string)
        : row[column.id]}
    
  ))}

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);
};

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;
}

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

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

const Countries = () => (
  
    {(row, column) => }
  
);

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

const People = () => ;

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 {
  rowKey: keyof T;
  rows: T[];
  columns: Column[];
  children?: (row: T, column: Column) => React.JSX.Element | string;
  onRowClick?: (row: T) => void;
}

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


  {(row, column) => }

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! ?

Release Statement This article is reproduced at: https://dev.to/igbominadeveloper/how-to-create-a-custom-table-component-with-react-and-typescript-part-2-1hde?1 If there is any infringement, please contact study_golang @163.comdelete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3