Event Handling, Functions & Props
Event Handling, Functions & Props
Event handling enables the app to respond to user actions, such as clicks or selections. The app can use events to invoke functions, enabling the interface to be updated in real time.
Functions are pieces of code that execute some actions. They assist in structuring logic, such as calculations or data, and simplify the app, making it readable and maintainable.
Data flows between components via props (properties). They also render parts reusable and enable dynamic content to pass through the app.
import dayjs from "dayjs";
const currentDate = dayjs();
const calculateAge = (birthDate) => {
if (!birthDate) return { years: 0, months: 0 };
let years = currentDate.year() - birthDate.year();
let months = currentDate.month() - birthDate.month();
// If birthday month hasn't occurred yet this year
if (months < 0) {
years--;
months += 12;
}
// If the birthday day hasn't occurred yet in the current month
if (currentDate.date() < birthDate.date()) {
months--;
if (months < 0) {
years--;
months += 12;
}
}
return { years, months };
};
<DatePicker value={dob} maxDate={currentDate} onChange={(newValue) => setDob(newValue)} slotProps={{ textField: { sx: { bgcolor: "#fff" } } }}
<p className="text-base md:text-xl p-2 lg:p-3">
Your age is:{" "}
{dob
? (() => {
const { years, months } = calculateAge(dob);
if (years === 0) return `${months} months`;
if (months === 0) return `${years} years`;
return `${years} years ${months} months`;
})()
: ""}
</p>Explanation:
1 - When the page loads, dayjs() stores today’s date in currentDate.
2 - The DatePicker shows an empty field because the dob (date of birth state) has not been selected yet.
3 - When the user selects a date, the onChange event is triggered. It sends the selected date as newValue, and setDob(newValue) updates the state.
4 - Because the state changes, React re-renders the component. The value={dob} keeps the DatePicker controlled by state, maxDate={currentDate} prevents selecting future dates, and slotProps only styles the input field (white background).
5 - After re-rendering, if dob exists, the calculateAge(dob) function runs.
- The function first checks if birthDate exists; if not, it immediately returns { years: 0, months: 0 } to prevent errors.
- Then it calculates the raw difference in years by subtracting the birth year from the current year, and the raw difference in months by subtracting the birth month from the current month.
- If the month's value becomes negative, it means the birthday month hasn’t occurred yet this year, so it decreases the year by 1 and adds 12 to the month to correct it.
- After that, it checks whether the current day of the month is less than the birth day; if so, the full month hasn’t completed yet, so it reduces by 1 more month.
- If this makes the months negative again, it reduces one year and adds 12 months to adjust properly. Finally, it returns the corrected years-and-months object.










