Home > OS >  In the below code, unable to set the value in datapicker using onchange event and name attribute
In the below code, unable to set the value in datapicker using onchange event and name attribute

Time:10-02

```
const initialValues = {
    code: '',
    product: '',
    checked: 'false',
    jobCardNo: '',
    openDate: '',
    completionDate: '',
    serial: '',
    technicalNo: '',
    lineNo: '',
    show: false,
  };
  const [values, setValues] = useState(initialValues);

  const handleInput = (e: { target: { name: any; value: any } }) => {
    const { name, value } = e.target;
    setValues({
      ...values,
      [name]: value,
    });
  };
```
const initialValues = {
    code: '',
    product: '',
    checked: 'false',
    jobCardNo: '',
    openDate: '',
    completionDate: '',
    serial: '',
    technicalNo: '',
    lineNo: '',
    show: false,
  };
  const [values, setValues] = useState(initialValues);

  const handleInput = (e: { target: { name: any; value: any } }) => {
    const { name, value } = e.target;
    setValues({
      ...values,
      [name]: value,
    });
  };

I am using the above object for handling the input fields, when coming to the Material UI date picker unable to do it. The name attribute doesnt exist in date picker. Any solution for this.Thanks in Advance

<DatePicker
 value={props.openDate}
 onChange={props.handleInput}
 renderInput={(params) => (
 <TextField name="openDate" {...params} />
 )}
 />

CodePudding user response:

MUI DatePicker's onChange function returns the first argument as the new value.

So, in your DatePicker you need to replace:

onChange={props.handleInput}

with this line:

onChange={(newValue) => props.handleInput({target: {name:"openDate", value: newValue}})}

in order to handle DatePicker with the same handleInput function with the TextField.

  • Related