Source Freeze

  • Home
  • iOS
  • Swift
  • Cross-Platform
  • About
  • Contact
Home » How to get the current Year in React

How to get the current Year in React

December 15, 2023 by Source Freeze Leave a Comment

In React, obtaining the current year may seem like a simple task, yet it plays a crucial role in various applications, especially when displaying dynamic content or creating time-sensitive features. We’ll explore two practical methods to achieve this: utilizing JavaScript’s Date object and leveraging React’s state management to update the year dynamically.

How to get the current Year in React
How to get the current Year in React

Using JavaScript’s Date Object

We’ll begin by defining a method, getCurrentYear, which utilizes the Date object to fetch the current year.

const getCurrentYear = () => {
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear();
  return currentYear;
};

Obtaining the Current Month

Similarly, we’ll create a function, getCurrentMonth, to retrieve the current month. Note that JavaScript’s getMonth() method returns the month starting from 0, hence the addition of 1 to display the correct month number.

const getCurrentMonth = () => {
  const currentDate = new Date();
  const currentMonth = currentDate.getMonth() + 1;
  return currentMonth;
};

Integrating Methods in a React Component

Now, let’s integrate these functions into a React component. This component will display the current year and month, updating them dynamically upon button clicks.

import React, { useState } from 'react';

const App = () => {
  const getCurrentYear = () => {
    const currentDate = new Date();
    const currentYear = currentDate.getFullYear();
    return currentYear;
  };

  const getCurrentMonth = () => {
    const currentDate = new Date();
    const currentMonth = currentDate.getMonth() + 1;
    return currentMonth;
  };

  const [year, setYear] = useState(0);
  const [month, setMonth] = useState(0);

  const updateYear = () => {
    const updatedYear = getCurrentYear();
    setYear(updatedYear);
  };

  const updateMonth = () => {
    const updatedMonth = getCurrentMonth();
    setMonth(updatedMonth);
  };

  return (
    <div>
      <p>Current Year: {year}</p>
      <button onClick={updateYear}>Update Year</button>
      <p>Current Month: {month}</p>
      <button onClick={updateMonth}>Update Month</button>
    </div>
  );
};

export default App;

Result:

Here’s how the page looks like before we click the buttons:

Screenshot as page loads

After clicking the buttons and getting updated values(It’s December 2023 for me while writing):

Code Explanation:

Let’s break down the code and explanation into concise points to delve deeper into howthe App component operates:

State Initialization:

  • const [year, setYear] = useState(0);
    • Initializes the year state using useState hook with an initial value of 0.
    • setYear is the function used to update the year state.
  • const [month, setMonth] = useState(0);
    • Initializes the month state using useState hook with an initial value of 0.
    • setMonth is the function used to update the month state.

Getting the year using const getCurrentYear = () => { … }

  • Defines a function getCurrentYear that uses the Date object to retrieve the current year.
  • getCurrentYear() returns the current year value.

Getting the month const getCurrentMonth = () => { … }

  • Defines a function getCurrentMonth that uses the Date object to retrieve the current month.
  • The month retrieved is incremented by 1 to match standard month numbers (January as 1, February as 2, and so on).

Updating year using const updateYear = () => { … }

  • Defines a function updateYear to update the year state.
  • Calls getCurrentYear() to fetch the current year and uses setYear to update the state.

Updating month const updateMonth = () => { … }

  • Defines a function updateMonth to update the month state.
  • Calls getCurrentMonth() to fetch the current month and uses setMonth to update the state.

Return Statement:

  • JSX Structure:
    • Renders a <div> containing:
      • <p> displaying the current year: Current Year: {year}
      • <button> triggering updateYear function on click: Update Year
      • <p> displaying the current month: Current Month: {month}
      • <button> triggering updateMonth function on click: Update Month

Event Handling:

  • onClick Events:
    • When the Update Year button is clicked, it triggers the updateYear function, updating the year state with the current year.
    • When the Update Month button is clicked, it triggers the updateMonth function, updating the month state with the current month.

Conclusion

In this blog, we explored practical methods using JavaScript’s Date object and React’s state management to dynamically retrieve and display the current year and month in a React application. Leveraging these methods provides a seamless way to showcase real-time date information and enables easy updates through user interactions.

Also checkout:

  • Capitalize First letter in JavaScript
  • Remove all Classes from an Element in JavaScript
  • Append Text to a Textarea in JavaScript
  • How to create a style tag using JavaScript
  • Remove all Classes from an Element in JavaScript
  • Hide/Show an Element in JavaScript

Filed Under: ios-tutorial

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How to Generate random numbers in JavaScript
  • How to Scroll to an Element in a React Component?
  • How to get a Date without the Time in JavaScript
  • How to modify url without reloading the page using javascript
  • How to disable server side rendering in nextjs
  • How to get a file type from URL in JavaScript

Recent Posts

  • How to Generate random numbers in JavaScript
  • How to Scroll to an Element in a React Component?
  • How to get a Date without the Time in JavaScript
  • How to modify url without reloading the page using javascript
  • How to disable server side rendering in nextjs
  • How to get a file type from URL in JavaScript

Recent Comments

    Tags

    beginner colon cross-platform es6 function html ionic iOS javascript mobile application development nextjs objective-c swift switch ternary typescript uiwebview Visual Studio plugin web developer

    Copyright © 2025 Source Freeze