import React, { useState, useEffect } from 'react';
import './style.css';
export default function App() {
const [daySel, setDaySel] = useState(new Date());
const [currentMonth, setCurrentMonth] = useState([]);
const [month, setMonth] = useState(new Date().getMonth());
const [year, setYear] = useState(new Date().getFullYear());
const days = [
{ id: 0, day: 'SUN' },
{ id: 1, day: 'MON' },
{ id: 2, day: 'TUE' },
{ id: 3, day: 'WED' },
{ id: 4, day: 'THR' },
{ id: 5, day: 'FRI' },
{ id: 6, day: 'SAT' },
];
const buildCalenderForMonth = (year, month) => {
let firstDate = new Date(year, month, 1);
let firstDay = firstDate.getDay();
let totalNoOfDays = new Date(year, month + 1, 0).getDate();
let lastDate = new Date(year, month, totalNoOfDays);
let lastDay = lastDate.getDay();
let totalNoOfDaysPreviousMonth = new Date(year, month, 0).getDate();
let calenderMonthArr = [];
// previous months date
for (let i = 0; i <= firstDay - 1; i++) {
let calMonth = {
date: totalNoOfDaysPreviousMonth - (firstDay - 1) + i,
isActive: false,
};
calenderMonthArr.push(calMonth);
}
// current months date
for (let i = 1; i <= totalNoOfDays; i++) {
let calMonth = {
date: i,
isActive: true,
};
calenderMonthArr.push(calMonth);
}
// next months date
let dy = 1;
for (let i = lastDay; i < days.length - 1; i++) {
let calMonth = {
date: dy,
isActive: false,
};
calenderMonthArr.push(calMonth);
dy++;
}
setCurrentMonth(calenderMonthArr);
};
useEffect(() => {
buildCalenderForMonth(year, month);
}, []);
const dateClick = (day) => {
let firstDate = new Date(year, month, day);
setDaySel(firstDate);
};
const onPrevMonth = () => {
let mnth = month - 1;
buildCalenderForMonth(year, month - 1);
setMonth(mnth);
};
const onNextMonth = () => {
let mnth = month + 1;
buildCalenderForMonth(year, mnth);
setMonth(mnth);
};
return (
<div>
<input id="input" type="text" value={daySel} /> <br />
<br />
<div id="div1">
<div className="days">
{days &&
days.length > 0 &&
days.map((item) => {
return <div key={item.id}>{item.day} </div>;
})}
</div>
<div className="showCal">
{currentMonth &&
currentMonth.length > 0 &&
currentMonth.map((item) => {
return (
<div
onClick={
item.isActive ? () => dateClick(item.date) : () => {}
}
className={`${item.isActive ? 'active' : 'inactive'}`}
key={item.id}
>
{item.date}{' '}
</div>
);
})}
</div>
<button id="prev" onClick={onPrevMonth}>
Prev
</button>
<button id="next" onClick={onNextMonth}>
Next
</button>
</div>
</div>
);
}
Good Article
ReplyDelete