I'm using the following Material-UI datepicker library:
import React from 'react'
import { MuiPickersUtilsProvider, KeyboardDatePicker } from "@material-ui/pickers";
import DateFnsUtils from "@date-io/date-fns";
import moment from 'moment';
export default function DatePicker(props) {
const { name, label, value, onChange } = props
const convertToDefEventPara = (name, value) => ({
target: {
name, value
}
})
return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker disableToolbar variant="inline" inputVariant="outlined"
label={label}
format="dd/MM/yyyy"
placeholder="DD/MM/YYYY"
name={name}
value={value}
onChange={date =>onChange(convertToDefEventPara(name,date))}
/>
</MuiPickersUtilsProvider>
)
}
Here is the handleInputChange
implementation that exists within useFrom
that I am using within my below component where I'm using DatePicker
import React, { useState } from 'react'
import { makeStyles } from "@material-ui/core";
export function useForm(initialFValues, validateOnChange = false, validate) {
const [values, setValues] = useState(initialFValues);
const [errors, setErrors] = useState({});
const handleInputChange = e => {
const { name, value } = e.target
setValues({
...values,
[name]: value
})
if (validateOnChange)
validate({ [name]: value })
}
const resetForm = () => {
setValues(initialFValues);
setErrors({})
}
return {
values,
setValues,
errors,
setErrors,
handleInputChange,
resetForm
}
}
const useStyles = makeStyles(theme => ({
root: {
'& .MuiFormControl-root': {
width: '80%',
margin: theme.spacing(1)
}
}
}))
export function Form(props) {
const classes = useStyles();
const { children, ...other } = props;
return (
<form className={classes.root} autoComplete="off" {...other}>
{props.children}
</form>
)
}
Within my actual component, I am using the DatePicker
as follows:
<DatePicker
name="last_changed"
label="Date last changed"
value={values.last_changed}
onChange={handleInputChange}
/>
My problem is, when I load the last_changed
date into state which has the value of "19/10/2021" back into this "Date last changed" field, I am receiving the error "Invalid date format" and don't understand why as I initially created this date, from this datepicker.
Any ideas what I could be doing wrong?
CodePudding user response:
You need to convert your date to js date string before sending it to your material-ui component by using Date toString() eventually
If you receive your date in that format '19/10/2021' maybe you can do this
const receivedDate = '19/10/2019';
const formatedDate = receivedDate.split('/').reverse().join('-');
const textDate = new Date(formatedDate).toString()