2

I am using TextField from material-ui, and I want to show current date in TextField, and also allow user to choose another date. If it is possible?

The value={date} do not appear in the TextField when using type="date". I have tried to find some help on the internet, but can't find anything. Code is below:

  • Any help is appreciated! And thanks in advance.

import React, { useState } from 'react';
import { TextField } from '@material-ui/core';
import { useForm } from 'react-hook-form';

export const AddDate: React.FC = () => {
    const [date, setDate] = useState(
        new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear(),
    );

    // handles when user changes input in date inputfield
    const handleChangeDate = (e: React.ChangeEvent<HTMLInputElement>): void => {
       setDate(e.target.value);
    };

    return(
        {/*Text field - date*/}
        <TextField
            name="date"
            id="date"
            label="Date"
            type="date"
            InputLabelProps={{ shrink: true }}
            inputRef={register}
            value={date}
            onChange={handleChangeDate}
            fullWidth
            required
          />
    );
};
lo7
  • 425
  • 2
  • 8
  • 21

2 Answers2

6

This works for me.

import React, { useState, useEffect } from "react";
import { TextField } from "@material-ui/core";
import "./styles.css";
import moment from 'moment';

const App =()=> {
  const [date, setDate] = useState(
    moment(new Date()).format("YYYY-MM-DD")
 );

 // handles when user changes input in date inputfield
 const handleChangeDate = e => {
    setDate(e.target.value);
 };

  console.log(date)

 return (
  <>
  <TextField
    name="date"
    id="date"
    label="Date"
    type="date"
    InputLabelProps={{ shrink: true }}
    value={date}
    onChange={handleChangeDate}
    fullWidth
    required
  />
</>
);
}

 export default App;

I just changed your code a little bit. Only change is comming from the useState. You just have to use moment js to convert the date into material-ui date type.

  • Thanks for this suggestion! I have tried this, and even though I have installed moment package, I get this error: "Module not found: Can't resolve 'moment' in '.../src/components/AddDate'". – lo7 Apr 16 '20 at 08:42
  • How did you install the moment package? – lo7 Apr 16 '20 at 08:42
  • 1
    This is how I installed the package. `npm install moment --save` Make sure you are importing moment. – Dushan Ranasinghage Apr 16 '20 at 08:49
1

You have to use MuiPickersUtilsProvider. Also, you should need date fomatter moment.js

import DateFnsUtils from '@date-io/date-fns';
import "react-datepicker/dist/react-datepicker.css";
import {
    MuiPickersUtilsProvider,
    KeyboardDatePicker,
} from '@material-ui/pickers';
import moment from 'moment';
import Input from '@material-ui/core/Input';

<MuiPickersUtilsProvider utils={DateFnsUtils}>
        <KeyboardDatePicker
            input={<Input/>}
            disableToolbar
            variant="inline"
            format="yyyy-mm-dd"
            margin="normal"
            value={value}
            onChange={event => {
                onValueChange(moment(event).format("YYYY-MM-DD"))
            }}
        />
</MuiPickersUtilsProvider>

install dependencies:

npm install @material-ui/pickers@3.2.8
npm install @date-io/date-fns@1.3.13
npm install date-fns@2.8.1
Nilanka Manoj
  • 3,527
  • 4
  • 17
  • 48
  • Alright thanks! But I get this error: "RangeError: Format string contains an unescaped latin alphabet character `n` (anonymous function) node_modules/date-fns/esm/format/index.js:421" – lo7 Apr 16 '20 at 08:16
  • I've tried to downgrade package, like they talk about here: (https://stackoverflow.com/questions/59600125/cannot-get-material-ui-datepicker-to-work). But the same error appears. – lo7 Apr 16 '20 at 08:19
  • have you added import for Input? I just added it to the answer – Nilanka Manoj Apr 16 '20 at 08:19
  • delete node modules folder and install what i have given in the answer – Nilanka Manoj Apr 16 '20 at 08:21
  • Deleted node modules and installed what you answered. Now there is a new error: "Type '{ input: Element; disableToolbar: true; variant: "inline"; format: string; margin: "normal"; value: Date; onChange: (event: Date) => void; }' is not assignable to type 'IntrinsicAttributes & DateValidationProps & BaseKeyboardPickerProps & { variant?: WrapperVariant; } & ... 4 more ... & { ...; }'. Property 'input' does not exist on type 'IntrinsicAttributes & DateValidationProps & BaseKeyboardPickerProps & { variant?: WrapperVariant; } & ... 4 more ... & { ...; }'. TS2322" – lo7 Apr 16 '20 at 08:34
  • It is because I use Typescript, but I don't know how to fix it, I am new to Typescript. – lo7 Apr 16 '20 at 08:35