Descripción general del selector de intervalo de fechas de React
El selector de intervalo de fechas Ignite UI for React es un componente ligero que incluye una entrada de texto y una ventana emergente de calendario, lo que permite a los usuarios seleccionar fácilmente las fechas de inicio y finalización. Es altamente personalizable para adaptarse a varios requisitos de la aplicación, ofreciendo características como restricciones de rango de fechas, formatos de fecha configurables y más.
Date Range Picker Example
Below is a sample demonstrating the IgrDateRangePicker component in action, where a calendar pop-up allows users to select start and end dates.
Empezando
To start using the IgrDateRangePicker, you first need to install the Ignite UI for React by running the following command:
npm install igniteui-react
After that, you need to import the IgrDateRangePicker and its necessary CSS, as follows:
import { IgrDateRangePicker } from 'igniteui-react';
import 'igniteui-webcomponents/themes/light/bootstrap.css';
Now you can start with a basic configuration of the React IgrDateRangePicker.
Para obtener una introducción completa a la Ignite UI for React, lea el tema Primeros pasos.
Usage
The IgrDateRangePicker allows users to select a start and end date either by choosing a date range from a dropdown/calendar pop-up or by typing directly into the input fields - one for the start date and one for the end date.
El selector ofrece dos modos para mostrar los valores de fecha: una sola entrada y dos entradas. En el modo de entrada única, el campo no se puede editar y el intervalo de fechas no se puede editar escribiendo. Sin embargo, en el modo de dos entradas, los usuarios pueden editar las fechas de inicio y finalización escribiendo campos de entrada separados.
Cuando el calendario está visible, se puede seleccionar un intervalo de fechas eligiendo una fecha de inicio y una fecha de finalización. Al seleccionar una fecha, se establecerá la fecha de inicio y finalización, y una vez que se elija una segunda fecha, se establecerá la fecha de finalización. Si ya hay un rango seleccionado, al hacer clic en cualquier otra fecha del calendario se iniciará una nueva selección de rango.
Display Date Range Picker
To instantiate a IgrDateRangePicker in its default single input mode, use the following code:
<IgrDateRangePicker/>
To switch the IgrDateRangePicker to use two inputs, set the useTwoInputs property to true.
<IgrDateRangePicker useTwoInputs/>
Value
In addition to being selected or typed by the user, the range value of the IgrDateRangePicker can also be set using the value property. It's important to note that the value must follow the format: { start: startDate, end: endDate }, where startDate and endDate are Date objects representing the selected range.
const dateRangeRef = useRef<IgrDateRangePicker>();
let startDate = new Date(2025, 4, 6);
let endDate = new Date(2025, 4, 8);
useEffect (() => {
dateRangeRef.current.value = { start: startDate, end: endDate }
}, [])
return (
<IgrDateRangePicker ref={dateRangeRef} />
);
In addition, the value can be set as attribute. In this case it should represent an object that can be parsed correctly as JSON, where the start and end fields should have date values in the ISO 8601 format:
<IgrDateRangePicker value={{start: new Date('2025-01-01'), end: new Date('2025-01-02')}}/>
Read-only & Non-editable
You can also make the IgrDateRangePicker read-only, which disables changing the range value through both typing and calendar selection, disables keyboard navigation, and makes the calendar and clear icons appear visually disabled. This is useful when the range is assigned via the value attribute and is intended to be display-only. To enable this behavior, simply set the readOnly property.
<IgrDateRangePicker useTwoInputs readOnly/>
Alternatively, you can use the nonEditable property, which, unlike readOnly, only prevents editing the input(s) via typing, while still allowing selection through the calendar and clearing via the clear icon.
<IgrDateRangePicker useTwoInputs nonEditable/>
Popup modes
By default, when clicked, the IgrDateRangePicker opens its calendar pop-up in dropdown mode. Alternatively, the calendar can be opened in dialog mode by setting the mode property to dialog.
<IgrDateRangePicker mode='dialog'/>
Keyboard Navigation
The IgrDateRangePicker features intuitive keyboard navigation, allowing users to easily increment, decrement, or jump between different component parts, all without needing to use a mouse.
Las opciones de navegación del teclado disponibles varían en función de si el componente está en modo de entrada única o de dos entradas.
Modo de dos entradas:
| Llaves | Descripción |
|---|---|
| ← | Mueve el símbolo de intercalación un carácter a la izquierda |
| → | Mueve el símbolo de intercalación un carácter a la derecha |
| CTRL + ArrowLeft | Mueve el símbolo de intercalación al principio de la sección de máscara de entrada actual o al principio de la anterior si ya está al principio |
| CTRL + ArrowRight | Mueve el símbolo de intercalación al final de la sección de máscara de entrada actual o al final de la siguiente si ya está al final |
| ArrowUp | Incrementa la parte actualmente "enfocada" de la máscara de entrada en un paso |
| ArrowDown | Disminuye la parte actualmente "enfocada" de la máscara de entrada en un paso |
| HOGAR | Mueve el símbolo de intercalación al principio de la máscara de entrada |
| FIN | Mueve el símbolo de intercalación al final de la máscara de entrada |
| CTRL +; | Establece la fecha actual como el valor del componente |
Modos de entrada simple y doble:
| Llaves | Descripción |
|---|---|
| ALT + ↓ | Opens the calendar dropdown |
| ALT + ↑ | Closes the calendar dropdown |
You can also navigate within the calendar pop-up using the keyboard. The navigation is the same as in the IgrCalendar component.
| Llaves | Descripción |
|---|---|
| ↑ / ↓ / ← / → | Navega a través de los días del mes |
| ENTER | Selecciona el día en el que se centra actualmente |
| PÁGINA ARRIBA | Pasa a la vista del mes anterior |
| PÁG ABAJO | Pasa a la vista del mes siguiente |
| SHIFT + PAGE UP | Se traslada al año anterior |
| SHIFT + PAGE DOWN | Pasa al año siguiente |
| HOGAR | Se centra en el primer día del mes actual que está a la vista (o el mes más antiguo en el que se muestra la vista de más de un mes) |
| FIN | Se centra en el último día del mes actual que está a la vista. (o el último mes cuando se muestra la vista de más de un mes) |
| Escape | Cierra la ventana emergente del calendario |
Layout
Label
You can define a label for the IgrDateRangePicker component using the label property when it is in single input mode. In two inputs mode, you can use the labelStart and labelEnd properties to define labels for the start and end date input fields, respectively.
<IgrDateRangePicker label='Date Range'/>
<IgrDateRangePicker useTwoInputs labelStart='Start Date' labelEnd='End Date'/>
Format
You also have the option to customize the date format displayed in the input fields. There are three properties available for this purpose: locale, inputFormat, and displayFormat.
The locale property allows you to set the desired locale identifier, which determines how the date is formatted based on regional conventions.
For example, to display the date in a Japanese format, you can set the locale property like this:
<IgrDateRangePicker locale='ja-JP'/>
If you want to manually define the date format, you can use the inputFormat property by passing a custom format string:
<IgrDateRangePicker inputFormat='dd/MM/yy'/>
The displayFormat property also accepts a custom format string, but it only applies when the input field is idle (i.e., not focused). When the field is focused, the format reverts to the default or to the one defined by inputFormat, if both properties are used together:
<IgrDateRangePicker inputFormat='dd/MM/yy' displayFormat='yy/MM/dd'/>
Calendar Layout and Formatting
You can further customize the pop-up calendar using various properties:
| Nombre | Tipo | Descripción |
|---|---|---|
orientation |
'vertical' or 'horizontal' | Permite establecer si el calendario debe visualizarse vertical u horizontalmente. |
visibleMonths |
cadena | Controla cuántos meses son visibles a la vez, con un valor de 1 o 2. |
showWeekNumbers |
cadena | Habilita o deshabilita la columna de número de semana en el calendario. |
open |
booleano | Determina si el selector de calendario está abierto. |
keepOpenOnSelect |
booleano | Mantiene abierto el selector de calendario después de seleccionar una fecha. |
keepOpenOnOutsideClick |
booleano | Mantiene abierto el selector de calendario al hacer clic fuera de él. |
weekStart |
cadena | Establece el día de inicio de la semana. |
hideOutsideDays |
booleano | Oculta los días que quedan fuera de la vista del mes actual. |
hideHeader |
booleano | Oculta el encabezado del calendario (aplicable solo en el modo de diálogo). |
headerOrientation |
'vertical' or 'horizontal' | Aligns the calendar header vertically or horizontally (dialog mode only). |
activeDate |
Fecha | Establece la fecha que se resalta inicialmente en el calendario. Si no se establece, la fecha actual se convierte en la fecha activa. |
<IgrDateRangePicker orientation='vertical' visibleMonths={1} showWeekNumbers/>
Min & Max
You can also set the min and max properties to restrict user input by disabling calendar dates outside the defined range. These properties act as validators, so even if the user manually types a date outside the range, the IgrDateRangePicker will become invalid.
<IgrDateRangePicker min={new Date('2025-05-06')} max={new Date('2025-05-10')}/>
Custom & Predefined Date Ranges
You can also add custom date range chips to the calendar pop-up for faster range selection using the customRanges property. For example, you can create a custom date range chip to quickly select the range for the upcoming 7 days, ending with the current date. In addition, by setting the usePredefinedRanges property, a set of predefined ranges chips will be displayed along with the custom ones.
const today = new Date();
const nextSeven = new Date(
today.getFullYear(),
today.getMonth(),
today.getDate() + 7
);
const nextWeek: CustomDateRange[] = [
{
label: "Next 7 days",
dateRange: {
start: today,
end: nextSeven
}
}
];
return (
<IgrDateRangePicker usePredefinedRanges customRanges={nextWeek} />
);
Ahora, cuando haga clic en el chip "Próximos 7 días" recién creado en la ventana emergente del calendario, el rango se seleccionará automáticamente, desde hoy hasta los próximos 7 días.
Disabled & Special dates
You also have the ability to set disabled dates in the calendar to narrow the range of dates the user can choose from. To set the disabled dates, you can use the disabledDates property.
const dateRangeRef = useRef<IgrDateRangePicker>();
const minDate = new Date(2025, 4, 5);
const maxDate = new Date(2025, 4, 15);
useEffect (() => {
dateRangeRef.current.disabledDates = [
{
type: DateRangeType.Between,
dateRange: [minDate, maxDate]
}
] as DateRangeDescriptor[];
}, [])
return (
<IgrDateRangePicker ref={dateRangeRef} />
);
Forms
The IgrDateRangePicker component can also be used seamlessly with the HTML form element. The min, max, and required properties act as form validators.
Additional configuration
Properties
In addition to the properties we've already covered, the IgrDateRangePicker component offers a variety of additional properties that allow you to further configure its behavior.
| Nombre | Tipo | Descripción |
|---|---|---|
disabled |
booleano | Deshabilita el componente. |
nonEditable |
booleano | Deshabilita la escritura en los campos de entrada. |
placeholder |
cadena | Texto de marcador de posición para el modo de entrada única. |
placeholderStart |
cadena | Texto de marcador de posición para la entrada de fecha de inicio (modo de dos entradas). |
placeholderEnd |
cadena | Texto de marcador de posición para la entrada de fecha de finalización (modo de dos entradas). |
outlined |
booleano | Determina si la parte de entrada tendrá apariencia de contorno en el tema Material. |
prompt |
cadena | Carácter de solicitud utilizado para las partes sin rellenar de la máscara de entrada. |
resourceStrings |
IgcDateRangePickerResourceStrings | Cadenas de recursos para la localización del selector de intervalo de fechas y el calendario. |
Slots
You also have the ability to add custom content and modify the appearance of the IgrDateRangePicker component using the available slots.
The prefix and suffix slots allow you to insert custom content before or after the input field (only available in single input mode):
<IgrDateRangePicker>
<IgrIcon slot='prefix' name='down_arrow_icon'></IgrIcon>
<IgrIcon slot='suffix' name='upload_icon'></IgrIcon>
</IgrDateRangePicker>
In two inputs mode, you can use the prefix-start, prefix-end, suffix-start, and suffix-end slots instead to target the individual inputs.
Another set of useful slots are clear-icon and calendar-icon, which allow you to customize the icons for the clear and calendar buttons in the input fields:
<IgrDateRangePicker>
<IgrIcon slot="clear-icon" name="apps_icon"></IgrIcon>
<IgrIcon slot="calendar-icon" name="bin_icon"></IgrIcon>
</IgrDateRangePicker>
In two inputs mode, you can also customize the default “to” text between the fields by using the separator slot:
<IgrDateRangePicker useTwoInputs>
<span slot='separator'>till</span>
</IgrDateRangePicker>
The actions slot allows you to insert a custom action button with your own logic. For example, the button below toggles week numbers column in the calendar:
const dateRangeRef = useRef<IgrDateRangePicker>();
const toggleWeekNumbers = () => {
dateRangeRef.current.showWeekNumbers = !dateRangeRef.current.showWeekNumbers;
};
return (
<IgrDateRangePicker ref={dateRangeRef}>
<IgrButton slot="actions" onClick={toggleWeekNumbers}>Toggle Week Numbers</IgrButton>
</IgrDateRangePicker>
);
In addition to the slots we've already covered, the following slots are also available in the IgrDateRangePicker component:
| Nombre | Descripción |
|---|---|
title |
Representa el contenido del título del calendario. Solo aplicable en el modo de diálogo. |
helper-text |
Renders content below the input field(s). |
header-date |
Reemplaza el texto de fecha/intervalo actual predeterminado en el encabezado del calendario. Solo aplicable en el modo de diálogo. |
clear-icon-start |
Icono de borrado personalizado para la entrada de inicio (modo de dos entradas). |
clear-icon-end |
Icono de borrado personalizado para la entrada final (modo de dos entradas). |
calendar-icon-start |
Icono de calendario personalizado para la entrada de inicio (modo de dos entradas). |
calendar-icon-end |
Icono de calendario personalizado para la entrada final (modo de dos entradas). |
calendar-icon-open |
Icono o contenido que se muestra cuando el selector está abierto (se aplica a ambas entradas en el modo de dos entradas). |
calendar-icon-open-start |
Icono o contenido para el estado abierto de la entrada de inicio (modo de dos entradas). |
calendar-icon-open-end |
Icono o contenido para el estado abierto de la entrada final (modo de dos entradas). |
Methods
In addition to the properties and slots, the IgrDateRangePicker also exposes few methods that you can use:
| Nombre | Descripción |
|---|---|
show |
Muestra el componente del selector de calendario. |
hide |
Hides the calendar picker component. |
toggle |
Alterna el selector de calendario entre los estados mostrado y oculto. |
clear |
Borra los campos de entrada, eliminando cualquier entrada del usuario. |
select |
Selecciona un valor de intervalo de fechas en el selector. |
setCustomValidity |
Establece un mensaje de validación personalizado. Si el mensaje proporcionado no está vacío, la entrada se marcará como no válida. |
Styling
Since the IgrDateRangePicker component uses the IgrCalendar component, it also inherits the Calendar's CSS parts, allowing you to style both components seamlessly. You can find the full list of exposed Calendar CSS parts here: Calendar Styling. In addition to the Calendar's CSS parts, the IgrDateRangePicker also exposes some unique CSS parts that you can use to customize its appearance:
| Nombre | Descripción |
|---|---|
separator |
El elemento separador entre las dos entradas. |
ranges |
El contenedor que representa los rangos personalizados y predefinidos. |
label |
El contenedor de etiquetas que representa el contenido por encima de la entrada de destino. |
container |
El contenedor principal que contiene todos los elementos de entrada principales. |
input |
El elemento de entrada nativo. |
prefix |
El contenedor de prefijo. |
suffix |
El contenedor del sufijo. |
calendar-icon |
El contenedor del icono de calendario para el estado cerrado. |
calendar-icon-start |
El envoltorio del icono de calendario para el estado cerrado de la entrada de inicio (dos entradas). |
calendar-icon-end |
El contenedor de iconos de calendario para el estado cerrado de la entrada final (dos entradas). |
calendar-icon-open |
El contenedor de iconos de calendario para el estado abierto. |
calendar-icon-open-start |
El envoltorio del icono de calendario para el estado abierto de la entrada de inicio (dos entradas). |
calendar-icon-open-end |
El contenedor de iconos de calendario para el estado abierto de la entrada final (dos entradas). |
clear-icon |
El envoltorio de icono transparente (entrada única). |
clear-icon-start |
El envoltorio de icono borrar para la entrada de inicio (dos entradas). |
clear-icon-end |
El envoltorio de icono borrado para la entrada final (dos entradas). |
actions |
El contenedor de acciones. |
helper-text |
El contenedor de texto auxiliar que representa el contenido debajo de la entrada de destino. |
igc-date-range-picker::part(label) {
color: var(--ig-gray-600);
}
igc-date-range-picker::part(calendar-icon-start),
igc-date-range-picker::part(calendar-icon-end) {
background-color: var(--ig-primary-500);
color: var(--ig-primary-500-contrast);
}
igc-date-range-picker::part(calendar-icon-open-start),
igc-date-range-picker::part(calendar-icon-open-end) {
background-color: var(--ig-primary-700);
color: var(--ig-primary-700-contrast);
}
igc-date-range-picker::part(clear-icon-start),
igc-date-range-picker::part(clear-icon-end) {
background-color: var(--ig-error-500);
color: var(--ig-error-500-contrast);
}