how to disable keyboard calender input in material ui datepicker reactjs

How to Disable Keyboard Calendar Input in Material UI Datepicker ReactJS

If you're using Material UI Datepicker in your ReactJS project, you might have noticed that it allows users to input the date via keyboard. However, sometimes you might want to disable this feature. Here's how you can do it:

Method 1: Using the disableToolbar property

You can use the disableToolbar property of the Material UI Datepicker component to disable the keyboard calendar input. Here's an example:


// Import the necessary components
import React, { useState } from 'react';
import { KeyboardDatePicker } from '@material-ui/pickers';

// Create a component
function MyDatePicker() {
  // Define a state variable to store the selected date
  const [selectedDate, setSelectedDate] = useState(null);

  return (
    <KeyboardDatePicker
      disableToolbar // Disable keyboard calendar input
      variant="inline"
      format="MM/dd/yyyy"
      margin="normal"
      id="date-picker-inline"
      label="Select a date"
      value={selectedDate}
      onChange={date => setSelectedDate(date)}
      KeyboardButtonProps={{
        'aria-label': 'change date',
      }}
    />
  );
}
  

Method 2: Using the readOnly property

If you want to disable only the keyboard input, but still allow users to select the date using the mouse, you can use the readOnly property of the input element. Here's an example:


// Import the necessary components
import React, { useState } from 'react';
import { KeyboardDatePicker } from '@material-ui/pickers';

// Create a component
function MyDatePicker() {
  // Define a state variable to store the selected date
  const [selectedDate, setSelectedDate] = useState(null);

  return (
    <KeyboardDatePicker
      variant="inline"
      format="MM/dd/yyyy"
      margin="normal"
      id="date-picker-inline"
      label="Select a date"
      value={selectedDate}
      onChange={date => setSelectedDate(date)}
      KeyboardButtonProps={{
        'aria-label': 'change date',
      }}
      TextFieldComponent={({ InputProps, ...props }) => (
        <TextField
          {...props}
          InputProps={{
            ...InputProps,
            readOnly: true, // Disable keyboard input
          }}
        />
      )}
    />
  );
}
  

These are the two methods you can use to disable keyboard calendar input in Material UI Datepicker ReactJS. Choose the one that suits your needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe