Open In App

React MUI MobileDateRangePicker API

Last Updated : 07 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

React MUI is a UI library that provides fully-loaded components, bringing our own design system to our production-ready components. MUI is a user interface library that provides predefined and customizable React components for faster and easy web development, these Material-UI components are based on top of Material Design by Google.

The MobileDateRangePicker component in React Material-UI is a specialized picker that allows a user to select a range of dates. This component provides a mobile-friendly interface for date range selection and works well on touch devices. Material UI provides a customizable <MobileDateRangePicker/> component that we can use for several purposes with the help of its props

Import Statement:

import { MobileDateRangePicker } from 
    '@mui/x-date-pickers-pro/MobileDateRangePicker';
// or
import { MobileDateRangePicker } from 
    '@mui/x-date-pickers-pro';

 

Props List: 

  • onChange: This is a callback function that is fired when the selected date changes. 
  • renderInput: This prop allows us to customize the rendered input. This is a function.
  • value: This is the value of the picker. The type of the value is an array.
  • acceptRegex: This is the regular expression that is used to detect “accepted” symbols.
  • calendars: These are the number of calendars that renders on the desktop.
  • className: This is the class name that is applied to the root component. The type of this prop is a string.
  • closeOnSelect: This is a boolean prop. If this is set to true, the popup or dialog will immediately close after submitting the full date.
  • components: This specifies the overridable components. The type of this prop is an object. The default value is an empty object.
  • componentsProps: This specifies the props used for each component slot. The type of this prop is an object. The default value of this prop is an empty object.
  • dayOfWeekFormatter:  This is a function that formats the day of the week displayed in the calendar header. The default value of this function is  (day) => day.charAt(0).toUpperCase() .
  • defaultCalendarMonth: This is used to display the default calendar month when the value is equal to null.
  • DialogProps: These are the props that are applied to the dialog component. The type of this prop is any.
  • disableAutoMonthSwitching: This is a boolean prop. If this is true, after selecting the start date calendar will not automatically switch to the month of the end date. The default value of this prop is false.
  • disabled: This is a boolean prop. If the value of this prop is set to true, the picker and text field are disabled. The default value of this prop is false.
  • disableFuture: This is a boolean prop. If this is set to true, the future days are disabled. The default value of this prop is false.
  • disableHighlightToday: This is a boolean prop. If this is set to true, today’s date is rendered without being highlighted with a circle. The default value of this prop is false.
  • disableMaskedInput: This is a boolean prop. If this is set to true, this disables the mask on the keyboard. This has to be used rarely. And you have to pass the proper mask for your format. The default value of this prop is false.
  • disableOpenPicker: This is a boolean prop. If this is set to true, it does not render the open picker button. The default value of this prop is false.
  • disablePast: This is a boolean prop. If this is set to true, the past days are disabled. The default value of this prop is false.
  • endText: This is the text for the end input label and toolbar placeholder. The type of this prop is ‘node’ and the default value of this prop is ‘End’.
  • getOpenDialogArialText: This is a function of getting the aria-label text for control that opens the picker dialog. The Aria-label text must include the selected date.
  • getViewSwitchingButtonText: This is a function of getting the aerial-label text for switching between the views button.
  • InputAdornmentProps: These are the props to pass to the keyboard input adornment. The type of this prop is an object.
  • inputFormat: This is a string that specifies the format of the input.
  • leftArrowButtonText: This is a string that specifies the left arrow icon aria-label text.
  • loading: This is a boolean prop. If this is set to true, it renders LoadingComponent in the calendar view instead of the list view. It can be used to preload information and display that information in a calendar. The default value of this prop is false.
  • mask: This is a custom mask. This can be used to override generate from format. The type of this prop is a string.
  • maxDate: This is the maximally selectable date. You cannot select a date that is greater than the maxDate.
  • minDate:  This is the minimally selectable date. You cannot select a date that is lesser than the minDate.
  • onAccept: This is a callback function that gets fired when the date is accepted.
  • onClose: This is a callback function that gets fired when the popup requests to be closed. This must be used in a controlled mode.
  • onError: This is a callback function that gets fired when the input value or new value prop validation returns a new validation error.
  • onMonthChange: This is a callback function that gets called whenever a user changes a month.
  • onOpen: This is a callback function that gets called whenever the popup requests to be opened. This should be used in a controlled mode.
  • onViewChange: This is a callback function that gets fired whenever a view gets changed.
  • open: This is a boolean prop. This controls the popup or dialog open state. The default value of this prop is false.
  • OpenPickerButtonProps: These are the props to pass to the keyboard adornment button. The type of this prop is an object.
  • readOnly: This is a boolean prop. This prop makes a picker read-only. The default value is false.
  • reduceAnimations: This is a boolean prop. This prop disables heavy animations.
  • renderDay: This is a function that is a custom renderer for days.
  • renderLoading: This is a function that displays the component when loading is true.
  • rifmFormatter: This is a function that is custom formatted to be passed into the Rifm component.
  • rightArrowButtonText: This is a string that displays the right arrow icon aria-label text.
  • onYearChange: This is a callback function that gets fired whenever a year gets changed.
  • shouldDisableDate:  This is a function that is used to disable specific dates.
  • shouldDisableMonth: This is a function that is used to disable specific dates.
  • shouldDisableYear: This is a function that is used to disable a specific year.
  • showDaysOutsideCurrentMonth: This is a boolean prop. If this is set to true, then the days outside the current month are displayed.
  • showToolbar: This is a boolean prop. If this is set to true, then it shows the toolbar even in desktop mode. The default value is false.
  • startText: This is a prop that specifies the text for the start input label and toolbar placeholder. The type of this prop is ‘node’ and the default value of this prop is ‘Start’.
  • toolbarFormat: This is a date format, that is displayed in a toolbar. The type of this prop is a string.
  • toolbarTitle: This is the title for the Mobile picker, which is displayed in the toolbar. The default value is ‘Select date ‘range’

Slots List: Here is a list of the available slots in the MobileDateRangePicker component:

  • ActionBar: The action bar, which is placed below picker views. The default value is PickersActionBar.
  • LeftArrowButton: This is a button that allows you to switch to the left view. The default value is IconButton.
  • LeftArrowIcon: This is an icon that appears in the view switch button on the left side. The default value is ArrowLeft.
  • OpenPickerIcon: This is an icon that is displayed in the open picker button. The default value is calendar or clock.
  • RightArrowButton: This is a button that allows you to switch to the right view. The default value is IconButton.
  • RightArrowIcon: This is an icon that is displayed on the right view switch button. The default value is ArrowRight.
  • SwitchViewButton: This is a button that is displayed to switch between different calendar views. The default value is IconButton.
  • SwitchViewIcon: This is the icon that appears in the SwitchViewButton. The default value is ArrowDropDown.

Syntax:

<MobileDateRangePicker
    value={value}
    onChange={(newValue) => {
        setValue(newValue);
    }}
    renderInput={(startProps, endProps) => (
        <React.Fragment>
            <TextField {...startProps} />
            <Box sx={{ mx: 2 }}> to </Box>
            <TextField {...endProps} />
        </React.Fragment>
    )}
/>

Installing React App:

Step 1: Create a React app using the following command.

npx create-react-app mobile-date-range-picker example

Step 2: Now get into the project directory.

cd mobile-date-range-picker-example

Installing Material-UI: Installing Material-UI’s source files via npm/yarn, and they take care of injecting CSS needed.

npm install @material-ui/core
OR
yarn add @material-ui/core

Installing the required package:

npm install @mui/material @emotion/react @emotion/styled
npm install @mui/x-date-pickers dayjs @mui/x-date-pickers-pro

Project Structure:

Project Structure

Step to run the application:

npm start

Example 1: 

  • App.js

Javascript




import * as React from "react";
  
import TextField from "@mui/material/TextField";
import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
import { LocalizationProvider } from 
    "@mui/x-date-pickers-pro";
import { AdapterDayjs } from 
    "@mui/x-date-pickers-pro/AdapterDayjs";
import { MobileDateRangePicker } from 
    "@mui/x-date-pickers-pro/MobileDateRangePicker";
  
export default function ResponsiveDateRangePicker() {
    const [value, setValue] = React.useState([null, null]);
  
    return (
        <Stack spacing={3}>
            <LocalizationProvider
                dateAdapter={AdapterDayjs}
                localeText={{
                    start: "Start Date",
                    end: "End date"
                }}
            >
                <h1 style={{ color: "green" }}>
                    GeeksForGeeks
                </h1>
                <h3>React MUI MobileDateRangePicker API</h3>
                <MobileDateRangePicker
                    value={value}
                    onChange={(newValue) => {
                        setValue(newValue);
                    }}
                    renderInput={(startProps, endProps) => (
                        <React.Fragment>
                            <TextField {...startProps} />
                            <Box sx={{ mx: 2 }}> to </Box>
                            <TextField {...endProps} />
                        </React.Fragment>
                    )}
                />
            </LocalizationProvider>
        </Stack>
    );
}


Output: 

Selecting date range

Example 2: These displayed days are customizable with the renderDay function prop. You can take advantage of the internal DateRangePickerDay component.

App.js 

Javascript




import * as React from 'react';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import { LocalizationProvider } from 
    '@mui/x-date-pickers-pro';
import { AdapterDayjs } from 
    '@mui/x-date-pickers-pro/AdapterDayjs';
import { StaticDateRangePicker } from 
    '@mui/x-date-pickers-pro/StaticDateRangePicker';
import { DateRangePickerDay as MuiDateRangePickerDay } 
    from '@mui/x-date-pickers-pro/DateRangePickerDay';
  
const DateRangePickerDay = styled(MuiDateRangePickerDay)(
    ({
        theme,
        isHighlighting,
        isStartOfHighlighting,
        isEndOfHighlighting,
        outsideCurrentMonth,
    }) => ({
        ...(!outsideCurrentMonth &&
            isHighlighting && {
            borderRadius: 0,
            backgroundColor: theme.palette.primary.main,
            color: theme.palette.common.white,
            '&:hover, &:focus': {
                backgroundColor: theme.palette.primary.dark,
            },
        }),
        ...(isStartOfHighlighting && {
            borderTopLeftRadius: '50%',
            borderBottomLeftRadius: '50%',
        }),
        ...(isEndOfHighlighting && {
            borderTopRightRadius: '50%',
            borderBottomRightRadius: '50%',
        }),
    }),
);
  
export default function CustomDateRangePickerDay() {
    const [value, setValue] = React.useState([null, null]);
  
    const renderWeekPickerDay = (date, dateRangePickerDayProps) => {
        return <DateRangePickerDay {...dateRangePickerDayProps} />;
    };
  
    return (
        <LocalizationProvider dateAdapter={AdapterDayjs}>
            <StaticDateRangePicker
                displayStaticWrapperAs="desktop"
                label="date range"
                value={value}
                onChange={(newValue) => setValue(newValue)}
                renderDay={renderWeekPickerDay}
                renderInput={(startProps, endProps) => (
                    <React.Fragment>
                        <TextField {...startProps} />
                        <Box sx={{ mx: 2 }}> to </Box>
                        <TextField {...endProps} />
                    </React.Fragment>
                )}
            />
        </LocalizationProvider>
    );
}


Output:

 

Reference: https://mui.com/x/api/date-pickers/mobile-date-range-picker/



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads