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:
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
/>
);
};
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments