I want to output the current date in my component.

Started 10 months ago by John in React JS

Output the current date in a customizable format with this component. Easily add formatted dates to your JavaScript projects, saving time and manual effort.

Body

export class DisplayDate extends React.Component {
    constructor() {
        super();
        var today = new Date(),
            date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
        this.state = {
            date: date
        };
    }

    render() {
        return (
            <h2>
                {this.state.date}
            </h2>
        );
    }
}

1 Replies

  • Replied 10 months ago

    Report

    Try this

    import React from 'react';
    
    class DisplayDate extends React.Component {
      constructor(props) {
        super(props);
        this.currentDate = new Date();
      }
    
      render() {
        return (
          <div>
            <h1>Current Date</h1>
            <p>{this.currentDate.toDateString()}</p>
          </div>
        );
      }
    }
    
    export default CurrentDate;