Fetching news headlines from an API and showing 10 news per page and theirs id's. which also refreshes in 10 seconds and new headlines come. TableHead mapping contents seems fine but tableBody providing this error:
Type 'string | Date' is not assignable to type 'ReactNode
//Init post
export interface InitPost {
title: string;
url: string;
created_at: Date;
author: string;
}
//state of post
const [posts, setPosts] = useState<InitPost[]>([]);
//colums
const columns: readonly Column[] = [
{ id: "title", label: "Title", minWidth: 170 },
{ id: "url", label: "URL", minWidth: 150 },
{ id: "created_at", label: "Created At", minWidth: 100 },
{ id: "author", label: "Author", minWidth: 100 },
];
Table head part: Fine
<TableHead>
<TableRow>
{columns.map((column) => (
<TableCell
key={column.id}
align={column.align}
style={{ minWidth: column.minWidth }}
>
{column.label}
</TableCell>
))}
<TableCell />
</TableRow>
</TableHead>
Error part
<TableBody>
{posts.map((row, index) => {
return (
<TableRow key={index}>
{columns.map((column) => {
const value = row[column.id];
****next line showing Error in "{value}"****
return <TableCell key={column.id}>{value}</TableCell>;
})}
<TableCell>
<Button
size="small"
variant="contained"
onClick={() => getDetails(row)}
>
Details
</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
CodePudding user response:
The primary issue is that a Date
type and string
type are incompatible.
Objects, with the exception of React Elements of course, are not valid as children
.
One of the columns you are rendering (created_at
) is of type Date
and cannot be used directly as a React Child.
You need to format the Date in some way or call the .toString()
method between the braces to ensure that your children
are not objects.
{
columns.map((column) => {
const value = row[column.id];
return <TableCell key={column.id}>{value.toString()}</TableCell>;
});
}