reactjsnext.jstimestampmomentjsdayjs

How to show relative time in react.js project


I'm building social media app using next.js. I want to display relative time in my project.

Expected output :

just now 2 minutes ago 1 hour ago 2 days

I want to retrieve time from MongoDB documentdocument

Tried to use moment and dayjs, but i'm facing some trouble in getting started. Can anyone help me?


Solution

  • You can use react-timeago:

    import TimeAgo from 'react-timeago';
    
    ...
    <TimeAgo date={date} />
    

    This will generate the auto-generated text that looks like:

    2 minutes ago
    3 days ago
    4 months ago
    1 year ago
    

    They also support custom formatting options.