IAspireToBeGladOS
IAspireToBeGladOS

Reputation: 1484

React - Console error with regards to Date format - "Objects are not valid as a React child"

I'm receiving this error in the console that's related to the "date" type:

Uncaught (in promise) Invariant Violation: Objects are not valid as a React child (found: Wed Mar 06 2019 18:24:58 GMT-0800 (Pacific Standard Time)). If you meant to render a collection of children, use an array instead.

The relevant bit of code that it's referencing:

const Conference = types
  .model('Conference', {
    id: types.identifyingNumber,
    date: types.Date,
    description: types.string,
  });

const conferenceStoreBase = types.model({ events: types.array(Event) });

And the content is being injected into another component like so:

const ConferenceDisplay = inject('conferenceStore')(observer(({ conferenceStore }) => (
<div>
  {
    conferenceStore.conference.map((conference) => {
      const {
        id,
        date,
        description,
      } = conference;

      return (
        <ul key={id}>
          <li>{date}</li>
          <li>{description}</li>
        </ul>
      );
    })
  }
</div>

From what I can tell, this has to do with needing to convert the Object into a string element. I'm new to React, so unsure how to proceed from here; any advice/guidance would be appreciated.

Upvotes: 0

Views: 302

Answers (1)

coreyward
coreyward

Reputation: 80128

The simplest way to convert a Date instance to a string for rendering is to use date.toLocaleDateString().

For example:

const today = new Date()
today.toLocaleDateString()
// result: "3/6/2019"

You could do this inside of your ConferenceDisplay functional component:

...
return (
  <ul key={id}>
    <li>{date.toLocaleDateString()}</li>
    <li>{description}</li>
  </ul>
)
...

Upvotes: 1

Related Questions