0

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??

2 Answers 2

2

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>
    )
  })
)
Sign up to request clarification or add additional context in comments.

Comments

0

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>
    )
  })
)

Comments

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.