whitebear
whitebear

Reputation: 12423

Use multiple lines javascript in React

I have this source code, in React function component

return (
  result.map(item => (
    <tr key={item.id}>
      <td>
      {new Date(item.pub_date).getFullYear()} /
      {new Date(item.pub_date).getMonth()} /
      {new Date(item.pub_date).getDate()}
      </td>
    </tr>

However in this script, it require three Date instances.

I want to shorten like this.

var date = new Date(item.pub_date)
date.getFullYear() / date.getMonth() /date.getDate()

Is it correct idea? or is it impossible to this in JSX??

Upvotes: 0

Views: 78

Answers (2)

Ugur Eren
Ugur Eren

Reputation: 2204

You can achieve what you want with a little different way with the use of template literals and setting date variable outside of the return scope.

return (
  result.map(item => {
    const date = new Date(item.pub_date)

    return (
      <tr key={item.id}>
        <td>
        {`${date.getFullYear()} / ${date.getMonth()} / ${date.getDate()}`}
        </td>
      </tr>
    )
  })
)

Upvotes: 2

NeERAJ TK
NeERAJ TK

Reputation: 2695

You can create a seperate function for formatting date:

function getDate(dateValue){
     let date = new Date(dateValue);
     return `${date.getFullYear()} / ${date.getMonth()} / ${date.getDate()}`
    }

return (
  result.map(item => {
    return (
      <tr key={item.id}>
        <td>
        {getDate(item.pub_date)}
        </td>
      </tr>
    )
  })
)

Upvotes: 0

Related Questions