site logo

Stacknatic

Stacknatic logo

We Care About Your Privacy

Stacknatic utilizes technologies, such as cookies, to enhance your browsing experience. By using this technology, you can be provided with a more personalized and seamless interaction with this website. By continuing, you agree with the Privacy Policy of Stacknatic.

Privacy Policy | Terms of Use
Conditionally Display Post Updated Date in React | Stacknatic
Home/blog/Conditionally Display Post Updated Date in React

Conditionally Display Post Updated Date in React

featured image for Conditionally Display Post Updated Date in React

Published on: April 20, 2024 (Updated on: August 12, 2024)

Table of Contents

  • Why show the updated date for a post or an article?
  • Common issue with date comparison
  • Proper way to conditionally show the 'updated' date for a post or article in React frontend

Have you noticed some websites show when a post was last changed? It's cool, right? Here's why it's a good idea and how to do it easily with TS or JS in React.

Why show the updated date for a post or an article?

Seeing when a post was last updated is great for users. It tells them the information is fresh. For websites with blogs or articles, updating old posts is common. When you show the updated date, people trust your content more. SEO wise, It even helps your website rank better on search engines. That's like a double win!

Common issue with date comparison

One common issue when comparing dates arises when your database is configured to automatically generates a modified date. In such cases, the modified date might be greater than the published date with a few milliseconds. Consequently, when attempting a simple comparison between the published and modified dates for conditional rendering, both dates may appear in your blog post, even for unmodified posts. Obviously this might not be your intended behaviour.

Proper way to conditionally show the 'updated' date for a post or article in React frontend

There are many ways to properly compare dates in React and the method you are going to use might depend on how the modified date is saved with your backend logic or rendered in the frontend. The solution here lets you compare dates with a simple logic. If you're more into JavaScript, no worries. You can use the same trick by skipping the type declaration.

First, create a function to convert the date to numbers only: 

const convertDateToNumbersOnly = (date: string) => {
    const dateObject = new Date(date);
    //get the date in the format of YYYYMMDD
    return dateObject.toISOString().replace(/[^0-9]/g, "").slice(0, 8);
}

In the above function, here's what happens:

A regular expression is used to remove all non-numeric characters from the ISO format of the date and returns the date and time (including hours, minutes) in pure numeric format. You would notice that the format is in 'YYYMMDD' so millisecond is omitted in order to prevent the common issue that was previously explained earlier.

Next create a function that conditionally displays the post 'updated' date if the post has been modified:

const postDate = () => {
    return convertDateToNumbersOnly(post.updated) >
      convertDateToNumbersOnly(post.date) ? (
      <p className="centered-text">
        Published on:{" "}
        {new Date(post.date).toLocaleDateString(undefined, {
          year: "numeric",
          month: "long",
          day: "numeric",
        })}
        <span>
          {" "}
          (Updated on:{" "}
          {new Date(post.updated).toLocaleDateString(undefined, {
            year: "numeric",
            month: "long",
            day: "numeric",
          })}
          )
        </span>
      </p>
    ) : (
      <p className="centered-text">
        Published on:{" "}
        {new Date(post.date).toLocaleDateString(undefined, {
          year: "numeric",
          month: "long",
          day: "numeric",
        })}
      </p>
    );
};

Then simply place postDate() in the relevant part of your code where you want the date to be displayed.

Here is an example for a react or Next.js application:

<header>
   <h1>Sample Post</h1>
           
   {postDate()}
</header>

 

See more posts in Websites
Author:author's avatarMichael

Recommended Posts

CIA Triad Simplified: Automated Workflow for Lawyers

Discover how law firms can automate CIA-triad security—confidentiality, integrity and availability—with encryption, blockchain anchoring and WORM retention.

featured image for How to Create a Django Web App (with Custom User Model)

How to Create a Django Web App (with Custom User Model)

Learn how to create a Django web app with a custom user model, covering setup and the essential steps to tailor your application to your needs.

featured image for CSRF Attack and Implications Explained in Simple Terms With Example

CSRF Attack and Implications Explained in Simple Terms With Example

An explanation of Cross-Site Request Forgery (CSRF) attack, its implications, and effective strategies to protect web applications from unauthorized actions.

featured image for How to Trap Focus in Next.js and React

How to Trap Focus in Next.js and React

Trapping focus ensures that keyboard users can navigate your component without losing focus elsewhere on the page. Learn how to trap focus in React and Next.js.

featured image for How to Implement Debouncing in Next.js

How to Implement Debouncing in Next.js

Debouncing can be used to prevent performance issues or data inaccuracies that may arise from multiple component renderings or repetitive user actions.

featured image for Mutable vs Immutable Data in JavaScript and React.js

Mutable vs Immutable Data in JavaScript and React.js

In programming, data structures can generally be classified as either mutable or immutable. Here is a simplified explanation of both in JavaScript and React.js.