To render a table from array I used
const Posts: NextPage = ({ posts}: any) => {
return (
<>
.....
<tbody>
{
posts.map((post: any) => {
const _date = new Date(post.expiryDate);
const _expiryDate = `${_date.getFullYear()}-${_date.getMonth()}-${_date.getDay()}`;
return <tr key={post._id} onClick={() => showDetails(post)}>
<td>{post.type}</td>
<td>{_expiryDate}</td>
</tr>;
})
}
</tbody>
And this works perfectly. On click of any row I pass the post data to new component to show the details.
So on the detail page I am using
<tr>
<td className="table-key">Expiry</td>
<td className="table-value">{post.expiryDate}</td>
{
const _date = new Date(post.expiryDate);
const _expiryDate = `${_date.getFullYear()}-${_date.getMonth()}-${_date.getDay()}`;
return <td className="table-value">{_expiryDate}</td>;
}
</tr>
but this is showing Expression expected
and on the console
Syntax error: Unexpected token
On the list page same kind of expression is working? What is the issue?
{}
in JSX which is Embedding Expressions in JSX
Using a {}
inside jsx is similar to return({})
, just like in normal js, you can't declare a new variable there, but with another map, filter you can.
This will throw an error because this expression is invalid inside that {}
.
You would need to render your code block inside another function:
const renderExpiryDate = () => {
const _date = new Date(post.expiryDate);
const _expiryDate = `${_date.getFullYear()}-${_date.getMonth()}-${_date.getDay()}`;
return <td className="table-value">{_expiryDate}</td>;
}
Then bring it down to JSX:
<tr>
<td className="table-key">Expiry</td>
<td className="table-value">{post.expiryDate}</td>
{renderExpiryDate()}
</tr>
In the first case, you won't get a similar error because your expression is inside a map function which is normal javascripts.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.