Issue with MaterialUI and ReactJS: MobileDatePicker does not close after selecting a date

After implementing closeOnSelect for selecting a date, I am encountering an issue where the date picker remains open even after selection. The only way to make it disappear is by either escaping or clicking the OK or Cancel buttons. This issue occurs on both desktop and mobile devices.

<LocalizationProvider dateAdapter={AdapterDateFns}>
<MobileDatePicker
style={{ width: '100%' }}
label={"Date From"}
inputFormat="dd/MM/yyyy"
closeOnSelect={true}
views={['day']}
value={abc}
renderInput={(params) => <TextFields {...params} fullWidth />}
/>
</LocalizationProvider>

Is there a solution to ensure that the date picker closes automatically after a date is selected?

Answer №1

To ensure the date picker does not close on selection, set the disableCloseOnSelect prop to false.

<LocalizationProvider dateAdapter={AdapterDateFns}>
   <MobileDatePicker
      style={{ width: '100%' }}
      label={"Date From"}
      inputFormat="dd/MM/yyyy"
      disableCloseOnSelect={false}
      views={['day']}
      value={abc}
      renderInput={(params) => <TextFields {...params} fullWidth />}
   />
</LocalizationProvider>

If you want to see a live example, check out this codesandbox https://codesandbox.io/s/date-picker-material-ui-forked-so0v14

Answer №2

I've implemented a small modification in your code. Hopefully, it will be beneficial to you:

  • Make sure to include the required props for your date picker, such as {onChange, value }
  • Remember that datePickers do not accept style as props in this context
import * as React from "react";
import TextField from "@mui/material/TextField";
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";

import { MobileDatePicker } from "@mui/x-date-pickers/MobileDatePicker";


export default function MaterialUIPickers() {
  const [value, setValue] = React.useState<Date | null>(
    new Date("2014-08-18T21:11:54")
  );

  const handleChange = (newValue: Date | null) => {
    setValue(newValue);
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <MobileDatePicker
        label={"Date From"}
        inputFormat="dd/MM/yyyy"
        value={value}
        views={["day"]}
        onChange={handleChange}
        renderInput={(params) => <TextField {...params} fullWidth />}
      />
    </LocalizationProvider>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

The base64 conversion for the image is overflowing from the upload image field in react-draft-wysiwyg

I have a functional react-draft-wysiwyg editor application that allows me to add images. However, I am currently encountering an issue which is detailed below: https://i.stack.imgur.com/HTjAc.png This is the code snippet of what I have attempted so far. ...

How can the required flag be integrated with rules validation in react-hook-form and material-ui (mui) for inputs?

Currently, I have implemented react-hook-forms for handling form functionality and validation in our application. On the other hand, we are utilizing MUI/Material-UI as our component library. One issue that arises is that MUI automatically adds a * to inpu ...

Is there a way to customize the styles for the material UI alert component?

My journey with Typescript is relatively new, and I've recently built a snackbar component using React Context. However, when attempting to set the Alert severity, I encountered this error: "Type 'string' is not assignable to type 'Colo ...

Utilize React.js ThemeProvider to dynamically change themes based on routing

Hey everyone, I have a question regarding changing the theme provider based on the route in my code snippet: const rootElement = document.getElementById('root'); ReactDOM.render( <ThemeProvider theme="MyThemes.default& ...

Error arises on Github when submitting a pull request due to a conflicted package

When facing conflicts in the package.json file while submitting a pull request, what is the best approach to resolve them? I usually attempt using git pull origin, but it tends to generate numerous merge commits. ...

Avoiding unlimited re-renders when using useEffect() in React - Tips and Strategies

As a new developer, I recently built a chat application using socket io. In my code, I have the useEffect hook set to only change when the socket changes. However, I also have setMessage within the body of useEffect(), with socket as a dependency. Unfortun ...

Why is my React app opening in Google Chrome instead of the API?

I have a link in my React app that is supposed to open a PDF in another page, but for some reason Google Chrome is redirecting me to the React application instead of opening the API endpoint that renders the PDF. The URL for the PDF is /api/file/:_id and m ...

Is it possible to use both material-ui@next and the previous version concurrently?

I need some advice on a project I am working on that utilizes material-ui@next (v1). While I appreciate the new features in the latest autocomplete, I find it too complex for my needs. Instead, I would like to revert back to the older version of the autoco ...

Material UI React Autocomplete Component

I'm currently working on integrating an Autocomplete component using the Material UI library. However, I've encountered a challenge - I'm unsure of how to properly pass the value and onChange functions, especially since I have a custom Text ...

Upon attempting to add a new component, an error was encountered: Uncaught SyntaxError: Unexpected token export

I have created a React test project and added modules to my package.json as follows: { "name": "untitled", "version": "0.1.0", "private": true, "devDependencies": { "babel-preset-node5": "^12.0.1", "react-scripts": "0.9.5" }, "depe ...

ReactJS Application: Issue with Selective Mobile Scrolling

I've been working on a ReactJS web app where we mainly use styled-components for styling, but also sometimes utilize index.css for global styles (such as body and html). The application consists of an app header, a page header, and a container with a ...

What could be the reason for the failure of .simulate("mouseover") in a Jest / Enzyme test?

I have a scenario where a material-ui ListItem triggers the display of a material-ui Popper containing another ListItem on mouse over using the onMouseOver event. While this functionality works as expected, I am facing difficulties replicating the behavior ...

React video recording not displaying in the video element

I'm currently developing a React application that facilitates webcam interviews with candidates. As part of this process, candidates have the option to "Start Again" or "Complete" their interviews. One challenge I am facing is displaying the recorded ...

Encountering a TypeError in Material UI React Autocomplete

I tried using the demo code from here in my application, but it's not functioning as expected. I'm unsure of the differences between my code and the example on the website. The errors I'm encountering are: react-dom.development.js:14724 Unc ...

Is there a way to restrict my input to only 10 numbers without allowing any characters?

Is there a way to restrict the phone number input to only allow 10 numbers and exclude any other characters? Currently, setting the maxLength attribute limits the characters to 10 but allows additional characters as well. If I change the type attribute to ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

React JS for loop not displaying any output

I am trying to create a component that loops from 0 to the value entered as a prop. if (props.number !== "" && props.toPow !== "") { for (let i = 0; i < props.toPow; i++) { return ( <div> & ...

What is the best way to implement the Snackbar functionality within a class-based component?

My snackbar codes are not working as expected when I click the "confirm" button. I want the snackbar to appear after clicking the button. Most examples I've seen use functional components, so how can I get the Snackbar to work properly in a class comp ...

The callbackFinished function is not defined in the winwheel library

Every time I attempt to call a function with the callbackFinished property inside the animation of winwheel, I encounter an error stating that the function is not defined, even though it is defined in the same class. import React from 'react' imp ...