We we need to add the current date to <DayPicker> component with the selected state. Also, we want to make sure the user always select a day, they recommend to use the required param.
Step by step
In javascript, to get the current date we case use the Date function. We can console.log the date to make sure we're doing it right.
const today = new Date();
console.log("today: ", today)
After having the today date, we can use it to inicialize the value of our state.
If we refresh the page now we can see that nothing is broking.
To make sure we always have a day selected, we can use the required param in the <DayPicker> component. This will make impossible to unselect a date. We can change the day but cannot remove the selected day.
Take in consideration that we might have more param in <DayPicker> in our code. We should add required plus all the other params we have.
Test the new day picker. Make sure the current day is selected by default. Make sure you cannot unselect the day. Make sure you can select a different day.
Food for thought
What is the required param really doing? Try to remove the required param and test. Unselect the current day in the calendar by clicking the day. Add again the required param and try to unselect the day. Make sure you understand what's happening.
When we create a new calendar day the date picker starts empty, without any day selected.
Since most of the time we want to create an entry for today, we want to make the calendar have the today date selected by default.
To make this possible, the component we are using, the
<DayPicker>
have some params we can use.Here is how to do this: https://react-day-picker.js.org/basics/selecting-days#making-a-selection-required
We we need to add the current date to
<DayPicker>
component with theselected
state. Also, we want to make sure the user always select a day, they recommend to use therequired
param.Step by step
In javascript, to get the current date we case use the
Date
function. We canconsole.log
the date to make sure we're doing it right.After having the
today
date, we can use it to inicialize the value of our state.If we refresh the page now we can see that nothing is broking.
To make sure we always have a day selected, we can use the
required
param in the<DayPicker>
component. This will make impossible to unselect a date. We can change the day but cannot remove the selected day.Take in consideration that we might have more param in
<DayPicker>
in our code. We should addrequired
plus all the other params we have.Test the new day picker. Make sure the current day is selected by default. Make sure you cannot unselect the day. Make sure you can select a different day.
Food for thought
What is the
required
param really doing? Try to remove therequired
param and test. Unselect the current day in the calendar by clicking the day. Add again therequired
param and try to unselect the day. Make sure you understand what's happening.