0

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?

2
  • Can you show the list page? Commented Aug 26, 2021 at 4:49
  • @RyanLe, updaetd the question, Commented Aug 26, 2021 at 4:56

1 Answer 1

1

In your error case, you are using {} 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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer, in the second case, still i am using javascipt, decalred some variables and returned html, :(
It's a bit different, a {} inside JSX is already return ({}). just like in js, you can't declare a new variable inside that block. But with another map, filter..etc. You can

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.