Capture and set the new value of the Datetime picker in MUI upon user's acceptance click

import React from 'react'
import { Stack, Typography } from '@mui/material'
import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker'
import { renderTimeViewClock } from '@mui/x-date-pickers/timeViewRenderers'
import dayjs, { Dayjs } from 'dayjs'

interface ResponsiveDateTimePickerProps {
  value: Dayjs | null
  maxDateTime: Dayjs | null
  minDateTime: Dayjs | null
  disabled?: boolean
  label?: string
  onAccept: (date: Dayjs | null) => void
}

const ResponsiveDateTimePicker: React.FunctionComponent<
  ResponsiveDateTimePickerProps
> = ({ value, maxDateTime, minDateTime, disabled, label, onAccept }) => {
  type textFieldSizes = 'small' | 'medium' | undefined
  type actionBarOptions = 'today' | 'accept'

  const dateTimePickerProps = {
    viewRenderers: !label
      ? {
          hours: renderTimeViewClock,
          minutes: renderTimeViewClock,
          seconds: renderTimeViewClock,
        }
      : undefined,
    value,
    maxDateTime: maxDateTime || undefined,
    minDateTime: minDateTime || undefined,
    onAccept: (date: unknown) => {
      if (dayjs.isDayjs(date)) {
        onAccept(date as Dayjs)
      } else {
        onAccept(null)
      }
    },
    format: 'DD MMMM YYYY, h:mm a',
    disabled,
    slotProps: {
      actionBar: {
        actions: ['today' as actionBarOptions, 'accept' as actionBarOptions],
        sx: { padding: 0 },
      },
      textField: () => ({
        size: 'small' as textFieldSizes,
        InputProps: {
          placeholder: value ? '' : 'Forever',
          sx: {
            height: '40px',
          },
          slotProps: {
            input: {
              sx: {
                height: '21px !important',
                fontSize: '14px !important',
                padding: '8.5px 30px !important',
              },
            },
          },
        },
      }),
    },
  }

  return (
    <Stack direction="row" alignItems="center">
      {label && (
        <Typography
          variant="subtitle1"
          sx={{ minWidth: '120px' }}
          paddingRight={0}
        >
          {label}
        </Typography>
      )}
      <DateTimePicker {...dateTimePickerProps} />
    </Stack>
  )
}

export default ResponsiveDateTimePicker

While using the Datetime picker and displaying both the date and time parts in the picker, I have observed this sequence:

  • User clicks the picker to display it
  • User selects a date
  • User chooses an hour (and can pick am or pm)
  • User picks minutes (can also select am or pm here)

The issue is that when the user selects minutes, the function call is triggered immediately instead of waiting for the user to click "Accept". This disrupts the flow because I want the action to be executed only when the user explicitly clicks "Accept", allowing them to go back and adjust the hour if needed. How can I ensure that the function is called only when the user clicks "Accept" and not just by selecting minutes?

I would appreciate any help and guidance in resolving this issue. Thank you.

Answer №1

One option available is utilizing the closeOnSelect

If set to true, the popover or modal will automatically close upon submitting the complete date.

By default, this feature is set to true for desktop and false for mobile devices (depending on the wrapper chosen and the desktopModeMediaQuery prop).

For more information, you can refer to the DateTimePicker API Documentation

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

The notify.js fails to display notifications in the event of an error

Why am I not receiving any error notifications even when there is an error message in the response object? $.ajax(settings).done(function (response) { if ( "error_message" in response ) { console.log(response); $.notify(" ...

Having issues with validating a form using Yup for a Checkbox input?

My form is built using mui, formik, and yup. If the input fields are empty (e.g. "surname") after clicking the submit button, an error is displayed. However, the issue arises when the checkbox for Terms of Service isn't checked as no error shows up. ...

Obtaining the referring URL after being redirected from one webpage to another

I have multiple pages redirecting to dev.php using a PHP header. I am curious about the source of the redirection. <?php header(Location: dev.php); ?> I attempted to use <?php print "You entered using a link on ".$_SERVER["HTTP_REFERER"]; ?> ...

What does the typeof keyword return when used with a variable in Typescript?

In TypeScript, a class can be defined as shown below: class Sup { static member: any; static log() { console.log('sup'); } } If you write the following code: let x = Sup; Why does the type of x show up as typeof Sup (hig ...

Issue with Jquery's .html() function not functioning properly when trying to select HTML

I am currently working on a piece of code that looks like this: $price = $(element) > $('.main_paket_price').attr('name'); alert($price); Basically, I am trying to select an element inside element which has the class main_paket_pri ...

I could use some assistance with iterating through an array that is passed as a parameter to a function

Compute the product of parameter b and each element in the array. This code snippet currently only returns 25. This is because element a[0], which is "5", is being multiplied by argument b, which is also "5". The desired output should be ...

The perplexing phenomena of Ajax jQuery errors

Hey there! I'm having a bit of trouble with ajax jquery and could use some guidance. $.ajax({ type:"get", url:"www.google.com", success: function(html) { alert("success"); }, error : function(request,status,error) { alert(st ...

What is the best approach for dynamically appending new elements to a JSON array using PHP?

I am facing an issue with the JSON below: [{"username":"User1","password":"Password"}, {"username":"User5","password":"passWord"},] The above JSON is generated using the PHP code snippet mentioned below: <?php $username = $_POST["username"]; ?>&l ...

How to prevent links from being affected by the Gooey effect in D3

Issue: When applying the Gooey effect, the links are also affected, resulting in a teardrop shape instead of a circle. The code snippet includes a dragged() function that allows users to detach node 1 from node 0 and reconnect them by dragging. The code s ...

A comprehensive guide on harnessing the power of server-sent events in express.js

After incorporating the express.js framework, I configured my REST server. Now, I am interested in integrating server-sent events (sse) into this server. However, upon implementing the sse package from npmjs.com, an error occurs. It seems that the error is ...

Exploring the context of file upload events and analyzing javascript functionality

Can you help me conditionally trigger the file upload dialog using JavaScript based on an Ajax response? <input type="file" id="Upload"> I have hidden the input element as I don't want to display the default file upload button. Instead, ther ...

Inconsistencies in grunt-ng-constant target operations

I encountered a strange issue with grunt-ng-constant where only 2 out of the 3 targets are working. Here is how my configuration is set up: grunt.initConfig({ ngconstant: { options: { space: ' ', wrap: '"use strict";&bso ...

Guide to using get() and res.sendFile() function to redirect webpages

Why is the page not redirecting properly? In my index.html file, I have this script: $.get( "/loginPage", function( data ) {}); The purpose of this script is to check if a user is logged in. If they are, it should redirect them to the lobbyPage. This is ...

Fill a dropdown menu with options from a JSON object, arranging them in ascending order

I have a JSON hash that I am using to populate a combo box with the following code: $.each(json_hash, function(key, value) { $("#select").append("<option value='" + key + "'>" + value + "</option>"); }); The functionality w ...

When attempting to use JQuery autocomplete, the loading process continues indefinitely without successfully triggering the intended function

Currently, I am utilizing JQuery autocomplete to invoke a PHP function via AJAX. Below is the code snippet I am working with: $("#client").autocomplete("get_course_list.php", { width: 260, matchContains: true, selectFirst: false }); Upon execution, ...

JavaScript popup menu with a redirect URL

I utilized Tinybox from this source for launching a popup webpage. I am hoping that when I click the links on the webpage, the popup will close itself and redirect to the link's URL. Here are my JavaScript and HTML codes: <script type="text/java ...

What is the best way to retrieve the nearest form data with jQuery after a child input has been modified?

I have a page with multiple forms, each containing several input checkboxes. When one of the form inputs changes, I want to gather all the parent form's data into a JSON array so that I can post it elsewhere. I'm having trouble putting the post ...

What is the method to assign an initial value to React.createRef()?

Scrolling management in my component is handled through a ref that represents the current scroll value. I've chosen to use refs instead of state and setState because using setState while the user is scrolling would result in a choppy and unresponsive ...

Managing headers for localhost with Access-Control-Allow-Origin

I've run into a challenge with my React app. I'm making endpoint calls to different servers and have withCredentials set to true to include a token/cookie in the requests. The issue arises when trying to make this work seamlessly on localhost. S ...

The user removal process is not functioning properly

I'm encountering an issue in my Angularfire project while trying to remove a user. The email and password are being passed correctly, but the method responsible for user removal isn't getting executed. Below is the snippet of code from my Authent ...