Skip to main content

Date picker

Examples

Check out the Usage section for details about how to design a date picker properly, and the different configuration options we provide.

Basic example

You can add an input that allows a user to enter a date either manually or through a calendar modal.

<DatePicker
label="Choose date"
onChange={(event, value) =>
console.log('The date chosen is', value.day, value.month, value.year)
}
/>

Min/Max example

You can limit the range of dates a user can select.

Note: This does not include validation, it only limits the options in a dropdown. A user can manually enter any date.
<DatePicker
label="Choose date"
minDate={{ day: 1, month: 1, year: 2022 }}
maxDate={{ day: 31, month: 12, year: 2023 }}
/>

Validation example

You can use the onChange property to call a function that updates stateMessages to display errors to the user.

The following example displays errors for invalid dates or dates that are not in 2022.

function DatePickerMinMaxValidation() {
const [validationMessages, setValidationMessages] = useState({});
const minDate = { day: 1, month: 1, year: 2022 }
const maxDate = { day: 31, month: 12, year: 2022 }

function JutroDateToString (date) {
return `${date.year}-${String(date.month).padStart(2, "0")}-${String(date.day).padStart(2, "0")}`
}

const parseErrorCode = (errorObject: {errorCode?:string}) => {
if (!errorObject){
return
}

const { errorCode } = errorObject

if (errorCode === 'INVALID_DATE') {
return { error: ['Please enter a valid date.'] };
}

if (errorCode === 'MIN_EXCEEDED') {
return { error: [`Please enter a date after ${JutroDateToString(minDate)}.`] };
}

if (errorCode === 'MAX_EXCEEDED') {
return { error: [`Please enter a date before ${JutroDateToString(maxDate)}.`] };
}
};

const onChange = useCallback((e, newValue, errorObject) => {
setValidationMessages({});
const errorDetected = parseErrorCode(errorObject)

if (errorDetected) {
setValidationMessages(errorDetected);
}
}, []);

return (
<DatePicker
label= "Choose date"
onChange={onChange}
minDate={minDate}
maxDate={maxDate}
stateMessages={validationMessages}
/>
);
}