The Material UI date range picker fails to close once a selection has been made

I'm currently using the Material UI date range picker, but I've encountered an issue. After selecting the dates, the date picker does not close automatically. How can I make it close once the dates are selected? I couldn't find any specific props that address this issue. Is this a bug or expected behavior? The date picker closes automatically in the material demo, so I'm puzzled as to why it's not working in my implementation.

**import React, { useEffect, useState } from 'react';
import { TextField } from '@material-ui/core';
import propTypes from 'prop-types';
import styled from 'styled-components';
import AdapterDateFns from '@mui/lab/AdapterDateFns';
import LocalizationProvider from '@mui/lab/LocalizationProvider';
import DateRangePicker from '@mui/lab/DateRangePicker';
import Box from '@mui/material/Box';
import { StyledButton } from '../../../../Components/Generics.styled';

const WhenShouldAdRunContainer = styled.div`
    display: flex;
    height: 400px;
    align-items: center;
    flex-direction: column;
`;

const Title = styled.div`
    margin-top: 100px;

    font-size: 23px;
    font-weight: bold;
    letter-spacing: 0px;
    color: #000000;
    opacity: 1;
    height: 50px;
    flex-direction: column;
    font-weight: bold;
    text-align: center;
`;

const StyledNavButtons = styled.div`
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    width: 100%;
    max-width: 160px;
    margin-left: auto;
    margin-right: auto;
`;

const DatePickerContainer = styled.div`
    height: 70px;
    margin-left: auto;
    margin-right: auto;
    display: flex;
    flex-direction: row;
    justify-content: space-evenly;

    .MuiOutlinedInput-root {
        background-color: #fafbf7;
    }
`;

const WhenShouldAdRun = (props) => {
    const {
        campaignData,
        setCampaignData,
        handleNavButtonBack,
        handleNavButtonNext,
        setPageIndex,
    } = props;
    const [date, setDate] = useState([null, null]);

    const dateIsEmpty = date[0] === null || date[1] === null;

    const handleDateChange = (newValue) => {
        setDate(newValue);
    };

    useEffect(() => {
        if (date[0] && date[1]) {
            setCampaignData({
                ...campaignData,
                startDate: date[0].toISOString(),
                endDate: date[1].toISOString(),
            });
        }
    }, [date]);

    const aWeekFromToday = new Date(Date.now() + 3600 * 1000 * 168);

    const isMobileAd = campaignData.campaignTypeName === 'mobile';
    const isGoogleAd = campaignData.campaignTypeName === 'google';

    const handleNavButtonNextSkipUpload = () => {
        setPageIndex(6);
    };

    const determineRoute = () => {
        if (isMobileAd || isGoogleAd) {
            return handleNavButtonNextSkipUpload();
        }

        return handleNavButtonNext();
    };

    return (
        <WhenShouldAdRunContainer>
            <Title>When should your Ad run?</Title>
            <DatePickerContainer>
                <LocalizationProvider dateAdapter={AdapterDateFns}>
                    <DateRangePicker
                        startText="Start Date"
                        endText="End Date"
                        disableCloseOnSelect={false}
                        value={date}
                        minDate={aWeekFromToday}
                        onChange={(newValue) => {
                            handleDateChange(newValue);
                        }}
                        renderInput={(startProps, endProps) => (
                            <>
                                <TextField variant="outlined" {...startProps} />
                                <Box sx={{ mx: 2 }}> to </Box>
                                <TextField variant="outlined" {...endProps} />
                            </>
                        )}
                    />
                </LocalizationProvider>
            </DatePickerContainer>

            <StyledNavButtons>
                <StyledButton
                    variant="contained"
                    color="primary"
                    onClick={() => handleNavButtonBack()}
                >
                    Back
                </StyledButton>
                <StyledButton
                    variant="contained"
                    color="primary"
                    onClick={() => determineRoute()}
                    disabled={dateIsEmpty}
                >
                    Next
                </StyledButton>
            </StyledNavButtons>
        </WhenShouldAdRunContainer>
    );
};

WhenShouldAdRun.propTypes = {
    campaignData: propTypes.shape({
        startDate: propTypes.string,
        endDate: propTypes.string,
        campaignTypeName: propTypes.string,
    }),
    setCampaignData: propTypes.func,
    handleNavButtonNext: propTypes.func,
    handleNavButtonBack: propTypes.func,
    setPageIndex: propTypes.func,
};

WhenShouldAdRun.defaultProps = {
    campaignData: {},
    setCampaignData: () => {},
    handleNavButtonNext: () => {},
    handleNavButtonBack: () => {},
    setPageIndex: () => {},
};
export default WhenShouldAdRun;

Answer №1

To determine the behavior of closeOnSelect, set the prop value to true for desktop (using pointer actions) and false for mobile (with touch screen)

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 methods are available to incorporate arithmetic when defining a style attribute?

Is there a way to achieve arithmetic operations in CSS, like calculating margin-left: -60px + 50% of the width of the parent div? I'm eager to find a solution, whether it involves JavaScript or any other method. Any help would be greatly appreciated. ...

Changing the color of a selected list element using an Angular directive

I'm currently facing an issue with my directive that is supposed to turn a list element red when clicked. It works fine, but I also want it to revert back to black when another list item is selected, so only one item stays in red color. Here is how I ...

Managing click events on icons using Material-UI and ReactJS

Is there a way to retrieve the "name" of an icon button when it is clicked? I have been exploring material UI's options, but I am consistently getting "undefined" from the event handler import React from 'react' import {IconButton} from &a ...

Trouble with FilterBy Feature in Bootstrap-Table

I am attempting to use filtering functionality with a table that is populated via JSON, utilizing bootstrap-table by wenzhixin. HTML snippet: <button class="btn btn-primary" id="filterBtn">Filter</button> <div class="container"> &l ...

Challenges encountered when using promises for handling mysql query results

I've been working on creating a function that will return the value of a mysql query using promises. Here's what I have so far: query(query: string): string { var response = "No response..."; var sendRequest = (query:string): Prom ...

Is it possible for my JQueryUI draggable items to smoothly transition into a different overflowing element?

On my iPad, I have two scrollable areas where I kept the overflow to auto, scroll, or hidden to allow scrolling. One section contains unenrolled students, and using JQueryUI with touchPunch, I can drag a student from the unenrolled bin into their appropria ...

How to activate a button only if the specified conditions are met using VueJS 3

I'm currently facing challenges while working on a form to enable a button when certain conditions are met. The form I created includes fields for name, phone number, options, and a message. Once all requirements are filled, I aim to re-enable the di ...

Encountering an issue in react.js where pushing the URL with ID is not possible due to a missing dependency in the useEffect hook array

I am encountering an issue where I am unable to successfully push the id with history.push in my React application. Strangely, if I omit the id, everything works as expected. This problem is occurring while using react-router-dom version 5. useEffect(() =& ...

Is it essential to install npm react and react-dom when setting up a create-react-app project?

After going through the documentation on reactstrap, I found that it recommends installing npm packages with the following commands: npm install --save bootstrap npm install --save reactstrap react react-dom I'm wondering if it is actually required t ...

Avoiding model updates when cancelling in angular-xeditable

I am utilizing angular-xeditable. When changing the value of "editable-text" and pressing the Cancel button, the "editable-text" value should revert back to its previous one. In other words, "editable-text" keeps updating the model even if the Cancel butto ...

Dealing with Memory Issues in Google Apps Scripts

Currently, I am addressing a challenge within my organization that requires me to maintain some level of ambiguity. However, I have been granted permission to discuss this issue openly. The task at hand involves creating a script to analyze a Google Sheet ...

I am looking to identify when the focus event occurs on all HTML input elements on a page without using addEventListener or any HTML attributes

Does anyone know a way to detect the focus event on all HTML input elements on a page without using the addEventListener function or HTML attributes? I was successful in detecting click events with the following code: onclick = () => { // do somethi ...

Difficulty accessing class functions from the test application in Node.js NPM and Typescript

I created an NPM package to easily reuse a class. The package installs correctly and I can load the class, but unfortunately I am unable to access functions within the class. My project is built using TypeScript which compiles into a JavaScript class: For ...

The malfunction of CSS3 effect

I designed a website and used DIV CSS to call an image. .header_bottom_area { background: url(../img/HomepagePanels.jpg)no-repeat scroll center center; max-width: 100%; width: auto; height: 911px; } I would like to have the same image as shown in ...

I am currently experiencing difficulties with sending the image through my Next.js application on my Node.js backend

I am currently working on a next js application with the goal of sending image data, compression ratio, and output format from the frontend form to the backend (nodejs) application. The aim is for the backend to process this information and return the comp ...

What is the best way to create vertical spacing between Material UI Grid Paper components?

The spacing of the goal components is not as I would like it to be. This is how they currently appear. https://i.stack.imgur.com/jApzK.png So far, I have attempted setting the display of the Paper selector to flex. Additionally, I experimented with adjus ...

Trouble with triggering events from Datatable buttons

Below is the code snippet I am currently using for my DataTable : var oTable12= $('#example').DataTable({ "aaData": tableData, "aLengthMenu": [[5, 10, 20, -1], [5, 10, 20, "All"]], "iDisplayLength": 5, "aoColumnDefs ...

Get rid of the right border on the last child pseudo-class

I can't seem to figure this out. It's frustrating because I usually don't struggle with something as basic as a pseudo-class. My goal is to remove the right border of a div element for the last child. I've managed to make it work by ad ...

What is the best way to customize the spacing of grid lines in chartist.js?

I am struggling with chartist.js. I want to increase the spacing between y-axis gridlines by 40px. (Currently set at 36px) I have tried looking for examples, but haven't found any. .ct-grids line { stroke: #fff; opacity: .05; stroke-dasharray: ...

Materriel-UI ToggleButton has the appearance of a traditional button

Looking to style a ToggleButton like a button? Having trouble with an error in the console when nesting a button inside? Check out this solution: const StyledToggleButtonGroup = withStyles((theme) => ({ grouped: { margin: theme.spacing(0.5) ...