ST80
ST80

Reputation: 3903

ReactJS how to add momentJS to object attribute

How can I add MomentJS to an attribute inside an object in an ReactJS-app?

I tried to do this but it isn't working:

import moment from 'moment'

class View extends React.Component {
   constructor() {
    super()

    this.state = {
       data: [
        {
            "name" : "user1",
            "created" : "2017-05-18T12:55:18.6056923"
        }
      ]
   }

}

render() {
    return(
        <p>{this.state.data.createdTs.moment().format('DDDD Do YYYY, h:mm:ss a')}</p>
    )
 }

}

How can I achieve this?

Upvotes: 1

Views: 159

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281894

moment takes a date object as a parameter and your data is an array, if you want only the first option use

render() {
    return(
        <p>{moment(this.state.data[0].createdTs).format('DDDD Do YYYY, h:mm:ss a')}</p>
    )
 }

else map

render() {
    return(
        <p>{this.state.data.map((data) => {
             return <span>{moment(data.createdTs).format('DDDD Do YYYY, h:mm:ss a')}</span>
        })}</p>
    )
 }

Upvotes: 3

Related Questions