Ad

Format Date As Long Inside Reactjs Component

- 1 answer

I have a component like this

var Post = React.createClass({


render: function () {
    return (
      <li key={ this.props.message.uid }>
        <div className="avatar">
          <img src={ this.props.message.user.avatar } className="img-circle"/>
        </div>
        <div className="messages">
          <p>{ this.props.message.content }</p>
          <span className="date">{ "@"+this.props.message.user.login + " • " }</span>
          <span className="date timeago" title={ this.props.message.createdAt }>
            { this.props.message.createdAt }
          </span>
        </div>
      </li>
      )
  }
});

turns out that the createdAt is a string like 1451589259845 and I want to format the date. How can I do that on ReactJS? I tried put new Date() inside the brackets but got an error.

Ad

Answer

Just do it in JS the usual way, before you start your return, and just template that in:

render: function() {
  var cts = this.props.message.createdAt,
      cdate = (new Date(cts)).toString();
  return (
    ...
    <span ...>{ cdate }</span>
    ...
  );
}

And there are quite a few ways you can do the string formatting, Date has a number of them built in (like toLocaleString or toUTCString), or you can use a dedicated formatter like moment.js

Ad
source: stackoverflow.com
Ad