Jon Leopard
Jon Leopard

Reputation: 1014

React/date-fns - error in component 'Objects are not valid as a React child' when using 'addSuffix'

I've created a component that uses date-fns and the formatDistanceToNow method. It works fine but when I want use the addSuffix option, React throws the following error:

Unhandled Runtime Error Error: Objects are not valid as a React child (found: object with keys {addSuffix}). If you meant to render a collection of children, use an array instead.

import * as React from 'react'
import { format, parseISO, formatDistanceToNow } from 'date-fns';

function DateDistance({ text, dateString }) {
  const date = parseISO(dateString);
  return (
    <>
      <div className="text-xs font-medium text-gray-700">
        <span>{text}</span>
        <time>
          {(formatDistanceToNow(date), { addSuffix: true })}
        </time>
      </div>
    </>
  );
}

function BlogPost({ post }) {
  return (
   <>
    <h2>Hello World!</h2>
    <p>This will be the subheader and below will be the published and updated date values.</p>
    <DateDistance
      text="and was updated "
      dateString={post.updated_at}
    />
   </>
  )
}

Upvotes: 0

Views: 352

Answers (1)

Nikita Madeev
Nikita Madeev

Reputation: 4380

formatDistanceToNow(date, [options])

<time>{formatDistanceToNow(date, { addSuffix: true })}</time>

Upvotes: 1

Related Questions