0

I have the following code:

<div className=''>
  <div className='userLayout'>
  {localMessages.map((localMessage) => (
    <div className={`${userId}` === `${localMessage.uuid}` ? 'fromUserLayout userCurrentLayout' : 'fromUserLayout userOtherLayout'} >
      <div className={`${userId}` === `${localMessage.uuid}` ? 'user userCurrent' : 'user userOther'}>
      <p>{localMessage.content}</p>
      <p>{localMessage.timestamp}</p>
      { localMessage?.image && localMessage.image.length > 0 && <img style={{width: '100%', height: 'auth', marginBottom: 24 }} src={localMessage.image} alt='chat' /> } 
   </div>
  </div>)
  )}
</div>

which works, however, I want to convert my timestamp in localMessage.timestamp back to a date.
I know I could do this with something like:

let theDate = new Date(localMessage.timestamp)

but I can't remember (or figure out) how to use JS inside the map function.

I did try { let theDate = new Date(localMessage.timestamp) } but get parsing errors on the opening { (unexpected keyword 'let') and on theDate ( '}' expected)

3
  • 1
    Add braces? This is just basic arrow function syntax. Commented Apr 8, 2022 at 20:49
  • Also, just feel the need to remind that HTML != JSX. Within react you are dealing with JSX Commented Apr 8, 2022 at 20:50
  • Also that the best way to put JS inside your JSX return block is to not put JS inside your JSX return block. Instead, just do your work first, then stick the result of that work in one or more variables, and then template those into your JSX. Commented Apr 8, 2022 at 21:56

1 Answer 1

1

You can do:

<div className=''>
  <div className='userLayout'>
  {localMessages.map((localMessage) => (
    <div className={`${userId}` === `${localMessage.uuid}` ? 'fromUserLayout userCurrentLayout' : 'fromUserLayout userOtherLayout'} >
      <div className={`${userId}` === `${localMessage.uuid}` ? 'user userCurrent' : 'user userOther'}>
      <p>{localMessage.content}</p>

      <p>{new Date(localMessage.timestamp).toDateString()}</p>

      { localMessage?.image && localMessage.image.length > 0 && <img style={{width: '100%', height: 'auth', marginBottom: 24 }} src={localMessage.image} alt='chat' /> } 
   </div>
  </div>)
  )}
</div>

Or instead of using toDateString() you can use toLocaleString(),toLocaleDateString()... Doing just new Date(localMessage.timestamp) could return an object, which could reproduce an error inside a jsx tag.

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

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.