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:
To support this, the CustomTable
component will need some enhancements:
- The ability to format the rendered value—e.g., rendering a number with proper formatting.
- 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;
}
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",
},
];
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>
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;
}
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>
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<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>;
};
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>
);
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} />;
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;
}
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>
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! 🙌
Top comments (0)