Anjayluh
Anjayluh

Reputation: 1786

How can I open the mui KeyboardDatePicker dialog when the input field is clicked

Currently what happens is the datepicker is only opened when you click the calendar icon but i need it to open both when the input field is clicked and when the calendar icon is clicked. I have found that there is an onclick prop but I don't know how to add the function to trigger the dialog to open. Here is my code

<MuiPickersUtilsProvider utils={DateFnsUtils}>
  <KeyboardDatePicker
    variant="inline"
    fullWidth
    margin="normal"
    format={dateFormat}
    KeyboardButtonProps={{
      "aria-label": "change date",
    }}
    autoOk
    name={field.name}
    value={field.value || null}
    helperText={showError && error}
    error={Boolean(showError)}
    onClose={handleTouch}
    onChange={handleChange}
    onTouchEnd={handleTouch}
    onBlur={handleTouch}
    onClick={}
    PopoverProps={{
      anchorOrigin: { horizontal: "left", vertical: "bottom" },
      transformOrigin: { horizontal: "left", vertical: "top" },
    }}
    {...other}
  />
</MuiPickersUtilsProvider>

Upvotes: 3

Views: 9958

Answers (3)

Ivan Yulin
Ivan Yulin

Reputation: 1046

<MuiPickersUtilsProvider utils={DateFnsUtils}>
                <KeyboardDatePicker
                    InputProps={{readOnly: true}}
                    onClick={() => setIsPickerOpen(true)}
                    open={isYearPickerOpen}
                    onClose={() => setIsPickerOpen(false)} />
</MuiPickersUtilsProvider>

That's all to it.

Upvotes: 1

Taha
Taha

Reputation: 1242

I found a simple solution without refs

using open prop on KeyboardDatePickercomponent

The idea is to set the value to true onClick and to false onClose

source code :

 setPickerStatus = (status: boolean) => {
    this.setState({
      open: status
    });
  };

  render() {
    return (
      <KeyboardDatePicker
        onClick={() => this.setPickerStatus(true)}
        onClose={() => this.setPickerStatus(false)}
        open={this.state.open}
        ...
      />
    );
  }

Upvotes: 7

Khabir
Khabir

Reputation: 5854

if you want to open DatePicker after clicking on DatePicker then you dont need as it is auto opened by the library but if you want to execute some function during click then you can use onClick event. here is the example:

import 'date-fns';
import React from 'react';
import {MuiPickersUtilsProvider, KeyboardDatePicker} from '@material-ui/pickers';
import DateFnsUtils from '@date-io/date-fns';
import FormControl from "@material-ui/core/FormControl";

export default function KeyboardDatePickerExample(props) {

    function handleChange(e) {
        console.log(e);
    }

    function handleClick(e) {
        console.log(e, 'click');
    }

    return (
        <FormControl>
            <MuiPickersUtilsProvider utils={DateFnsUtils}>
                <KeyboardDatePicker
                    variant="inline"
                    fullWidth
                    margin="normal"
                    KeyboardButtonProps={{
                        "aria-label": "change date",
                    }}
                    autoOk
                    // value={field.value || null}
                    // onClose={handleTouch}
                    onChange={handleChange}
                    // onTouchEnd={handleTouch}
                    // onBlur={handleTouch}
                    onClick={handleClick}
                    PopoverProps={{
                        anchorOrigin: {horizontal: "left", vertical: "bottom"},
                        transformOrigin: {horizontal: "left", vertical: "top"},
                    }}
                />
            </MuiPickersUtilsProvider>
        </FormControl>
    )
}

But If you want to show DatePicker from outside click. Let's say you have button and you want to show DatePicker on that button click then you can follow the below example:

import * as Dom from 'react-dom';
import * as React from 'react';
import DatePickerDialog from 'material-ui/DatePicker/DatePickerDialog';
import {MuiThemeProvider} from 'material-ui/styles';

export class MyComponent extends React.Component {
    state = {
        selectedDate: new Date()
    };

    setDatePickerDialogReference = (ref) => {
        // React passes undefined/null if the reference has been unmounted.
        if (ref) {
            // Overwrite the dialog's handleRequestClose and handleWindowKeyUp functions.
            ref.handleWindowKeyUp = (...args) => console.log("Dialog tried to call handleWindowKeyUp.");
            ref.handleRequestClose = (...args) => console.log("Dialog tried to call handleRequestClose.");
        }

        this.datePickerDialog = ref;
    };

    openDatePicker = () => {
        this.datePickerDialog.show();
    };

    openDatePickerOnEnter = (e: React.KeyboardEvent<any>) => {
        if (e.key === "Enter") {
            this.openDatePicker();
        }
    };

    setDateReceived(date: Date) {
        this.setState({selectedDate: date});
    }

    render() {
        return (
            <div>
                <h1>{`Date Selected: ${this.state.selectedDate.toLocaleDateString()}`}</h1>
                <ol>
                    <li>{`Select the text field.`}</li>
                    <li>{`Press tab to select the button next.`}</li>
                    <li>{`Press enter with the button selected to open the DatePickerDialog.`}</li>
                </ol>
                <input
                    tabIndex={0}
                    type={"text"}
                    style={{width: 300, margin: "10px, 0"}}
                    value={"Select me, then press tab and enter."}
                    readOnly/>
                <div tabIndex={1}>
                    <button
                        type={"button"}
                        onKeyUp={e => this.openDatePickerOnEnter(e)}
                        onClick={e => this.openDatePicker()}>
                        {"Open DatePicker"}
                    </button>
                </div>
                <MuiThemeProvider>
                    <DatePickerDialog
                        ref={r => this.setDatePickerDialogReference(r)}
                        firstDayOfWeek={0 /* Must provide firstDayOfWeek or rendering of calendar will be broken. */}
                        autoOk={false}
                        onAccept={date => this.setDateReceived(date)}
                        initialDate={this.state.selectedDate}/>
                </MuiThemeProvider>
            </div>
        )
    }
}

Source

Updated Code

import * as Dom from 'react-dom';
import * as React from 'react';
import DatePickerDialog from 'material-ui/DatePicker/DatePickerDialog';
import {MuiThemeProvider} from 'material-ui/styles';

export class MyComponent extends React.Component {
    state = {
        selectedDate: new Date()
    };

    setDatePickerDialogReference = (ref) => {
        // React passes undefined/null if the reference has been unmounted.
        if (ref) {
            // Overwrite the dialog's handleRequestClose and handleWindowKeyUp functions.
            ref.handleWindowKeyUp = (...args) => console.log("Dialog tried to call handleWindowKeyUp.");
            ref.handleRequestClose = (...args) => console.log("Dialog tried to call handleRequestClose.");
        }

        this.datePickerDialog = ref;
    };

    openDatePicker = () => {
        this.datePickerDialog.show();
    };

    openDatePickerOnEnter = (e: React.KeyboardEvent<any>) => {
        if (e.key === "Enter") {
            this.openDatePicker();
        }
    };

    setDateReceived(date: Date) {
        this.setState({selectedDate: date});
    }

    render() {
        return (
            <div>
                <h1>{`Date Selected: ${this.state.selectedDate.toLocaleDateString()}`}</h1>
                <input
                    tabIndex={0}
                    type={"text"}
                    style={{width: 300, margin: "10px, 0"}}
                    value={"Select me, then press tab and enter."}
                    onClick={e => this.openDatePicker()} />
                <MuiThemeProvider>
                    <DatePickerDialog
                        ref={r => this.setDatePickerDialogReference(r)}
                        firstDayOfWeek={0 /* Must provide firstDayOfWeek or rendering of calendar will be broken. */}
                        autoOk={false}
                        onAccept={date => this.setDateReceived(date)}
                        initialDate={this.state.selectedDate}/>
                </MuiThemeProvider>
            </div>
        )
    }
}

Upvotes: 0

Related Questions