Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here is one way to retrieve the name of the previous month from an array in Reactjs:

  1. Create an array of month names:
const months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December',
];
  1. Get the current month index and subtract 1 to get the previous month index:
const currentDate = new Date();
const currentMonthIndex = currentDate.getMonth();
const previousMonthIndex = currentMonthIndex - 1;

Note: If the current month is January, the previous month will be December of the previous year.

  1. Handle edge cases where the previous month index is negative or greater than 11 (December):
let previousMonthName = '';

if (previousMonthIndex < 0) {
  // If previousMonthIndex is negative, set it to December of previous year
  previousMonthIndex = 11; // December
  currentDate.setFullYear(currentDate.getFullYear() - 1);
}

if (previousMonthIndex > 11) {
  // If previousMonthIndex is greater than 11, set it to January of next year
  previousMonthIndex = 0; // January
  currentDate.setFullYear(currentDate.getFullYear() + 1);
}

previousMonthName = months[previousMonthIndex];
  1. Render the previous month name:
return <div>Previous month: {previousMonthName}</div>;

This code will retrieve the name of the previous month from an array in Reactjs.