0

I have this code:

var message = "The event starts at {1}";
var startTime = <FormattedTime value={new Date(eventData.startDateTime)}/>;
message = message.replace("{1}", startTime);

return (
  <div>
    {message}
    <br/>
    <FormattedTime value={new Date(eventData.startDateTime)}/><br/>
  </div>                    
);

This prints as:

The event starts at [object Object]
5:55 PM

I have a feeling this has more to do with javascript than react, but... why does it print as [object Object] in one case and the correct time in another?

Is there a way to get my event string with the correct time?

Jeremy
  • 5,365
  • 14
  • 51
  • 80
  • 2
    You aren't rendering your `` object to HTML when you do `message.replace`, you are stringifying it. – Rob M. Aug 07 '17 at 22:10

2 Answers2

0

Since the problem is due to trying to use what's a dom object as a variable, one solution is to do the whole thing in HTML and do the string replace using intl's FormattedMessage. This only happens to work because I am already using something inside curly brackets for my strings that are to be substituted.

<FormattedMessage id="message" 
   defaultMessage="The event starts at {1}" 
   values={{ 1: startTime }}
/>
Jeremy
  • 5,365
  • 14
  • 51
  • 80
0

FormattedTime returns an object. If you want to return a string, you must use the function formatTime.

You can get it by calling the function injectInlt from 'react-intl' to your component. The function will be in this.props.intl.formatTime().

formatTime(Date.now()); // "4:03 PM"
Damien
  • 287
  • 1
  • 9