I am trying to make a calendar where, once the page loads, it has already gone through a function to get the current month. This is by using HTML format within React’s JS file.
<h2 onLoad={curMonth}></h2>
I have curMonth
being imported from a different file:
import { curMonth } from '../../calendar';
I will also include the function made, in case it would be some help to understand:
function curMonth() {
let monthName = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
let today = new Date();
let month = today.getMonth();
let listedMonth = document.querySelector(".calendar h2");
listedMonth.textContent = monthName[month];
}
export { curMonth };
Previously, I had a default set to <h2>September</h2>
, but it continued to stay "September" after the load was complete too, and I would also like for it to be the current month. Currently, it is at <h2 onLoad={curMonth}></h2>
but left empty after load.
I followed these two guides: react.dev and w3schools
Is it that <h2>
should not include the onLoad function? What is the reason why the function is not run on load?
>Solution :
This is more react way:
function curMonth() {
let monthName = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
let today = new Date();
let month = today.getMonth();
return monthName[month];
}
<h2>{curMonth()}</h2>