I am trying to create a calender that looks like the image but I am unable to do that. is there any better way to do this?
Here is my code (I am using moment to do this).
import React from 'react'
import moment from 'moment'
const Calender = () => {
const value = moment()
const startMonth = value.clone().startOf('year')
const endMonth = value.clone().endOf('year')
const month = startMonth.clone()
const calendar = [];
// while(startMonth.isBefore(endMonth, 'month')) {
// calendar.push(
// Array(7).fill(0).map(()=>month.add(1,'month').clone())
// )
// }
console.log('month ' month.format('MMM'));
while (month.format('MMM') === 'Dec') {
calendar.push(
// Array(12).map(()=>month.add(1,'month').clone())
console.log(month.add(1,'month'))
)
}
return ( <>
{console.log(calendar)}
<div>
{calendar}
{endMonth.format('MMM')}
</div>
</> );
}
export default Calender;
CodePudding user response:
import { useState } from "react";
import "./styles.css";
import Months from "./Months";
export default function App() {
const Years = [2015, 2016, 2017, 2018, 2019];
const [selected, setSelected] = useState({ month: "Feb", year: 2017 });
return (
<div className="App">
<div className="calendar">
{Years.map((year) => {
return (
<div key={year}>
<div
onClick={() => setSelected({ ...selected, year: year })}
className={selected.year === year ? "active-year" : "year"}
>
{year}
</div>
{selected.year === year && (
<Months setSelected={setSelected} selected={selected} />
)}
</div>
);
})}
</div>
</div>
);
}
Months.js :
export default function Months({ selected, setSelected }) {
const Months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"June",
"July",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
return (
<div className="months">
{Months.map((month) => {
return (
<div
onClick={() => setSelected({ ...selected, month: month })}
className={selected.month === month ? "active-month" : "month"}
>
{month}
</div>
);
})}
</div>
);
}
live demo: https://codesandbox.io/s/goofy-flower-3bvn0