how change the dateformat of DatePicker - Material-UI (React) - reactjs

I'm using the datepicker from Material-UI, but the actual format is "mm/dd/yyyy" and I need to change that to "dd/mm/yyyy", how can I do it?
the component:
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
onError={(e) => {
setError(true);
}}
label="Date"
value={infos.date}
onChange={(newValue) => {
setInfos({ ...infos, date: newValue });
setError(false);
}}
renderInput={(params) => (
<TextField
color={error ? "error" : "primary"}
required
error={error}
helperText={error ? messageError.date : ""}
{...params}
/>
)}
/>
</LocalizationProvider>

try inputFormat:
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
inputFormat="dd/MM/yyyy"
onError={(e) => {
setError(true);
}}
label="Date"
value={infos.date}
onChange={(newValue) => {
setInfos({ ...infos, date: newValue });
setError(false);
}}
renderInput={(params) => (
<TextField
color={error ? "error" : "primary"}
required
error={error}
helperText={error ? messageError.date : ""}
{...params}
/>
)}
/>
</LocalizationProvider>

Related

user is able to type alpha characters in mobile , but in laptop is working fine

Here is code sample in Reactjs.
Is there problem with event.preventDefault(); ?
What should I try
please help me.
<Select
options={options}
components={{ DropdownIndicator, ValueContainer,IndicatorSeparator:() => null }}
styles={styles}
placeholder={placeholder}
onChange={(e)=> {onChange(e.value)}}
value={value}
defaultValue={defaultValue}
onKeyDown={(event) => {
if (!/[0-9]/.test(event.key) && event.key !== 'Backspace') {
event.preventDefault();
}
}}
/>
I have used onInputChange
<Select
options={options}
components={{ DropdownIndicator, ValueContainer,IndicatorSeparator:() => null }}
styles={styles}
placeholder={placeholder}
onChange={(e)=> {onChange(e.value)}}
value={value}
defaultValue={defaultValue}
onInputChange={(val) => {
return isNaN(val) ? '' : val; // only take number
}}

I want to disable end date picker before choosing start date picker in react js

Is it possible to disable the end date picker until the user enters the start date? Below I am sharing my code. Please tell me where I am doing wrong?
const startDate = new Date();
<Controller control={control} name="start_date" render={({ field }) => (
<DatePicker placeholderText="MM/dd/yyyy" dateFormat="MM/dd/yyyy"
onChange={(date) => field.onChange(date)} minDate={moment().toDate()}
selected={field.value}
id="start_dates"
required={true}
autoComplete='off'
onKeyDown={(e) => {
e.preventDefault();
}} />)}/>
<Controller control={control} name="end_date" render={({ field }) => (
<DatePicker dateFormat="MM/dd/yyyy"
onChange={(date) => field.onChange(date)}
disabled={startDate=== ""? true: false}
minDate={new Date(startDate)}
selected={field.value}
onKeyDown={(e) => {
e.preventDefault(); }} />)}/>
Create state variable dateStart.
In onChange event of startDate set its value, then disable endDate based on dateStart like this:
const [dateStart, setDateStart] = useState(null);
StartDate datepicker
<DatePicker placeholderText="MM/dd/yyyy" dateFormat="MM/dd/yyyy"
onChange={(date) => field.onChange(date); setDateStart(date)}
minDate={moment().toDate()}
selected={field.value}
id="start_dates"
required={true}
autoComplete='off'
onKeyDown={(e) => {
e.preventDefault();
}} />)}
/>
EndDate datepicker
<DatePicker dateFormat="MM/dd/yyyy"
onChange={(date) => field.onChange(date)}
disabled={dateStart ? false : true}
minDate={new Date(startDate)}
selected={field.value}
onKeyDown={(e) => {
e.preventDefault(); }} />)}
/>
Working example

React MUI datepicker gives me a datetime not a date

Even though I have initialized the format as a prop in DesktopDatePicker, when I change the value it comes like this: 2020-01-01T00:00:00.000Z
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DesktopDatePicker
inputVariant="outlined"
id="date-picker-dialog"
label="Birthday"
fullWidth
name="dob"
onChange={(val) => {
formik.setFieldValue("dob", val);
}}
renderInput={(params) => <TextField {...params} />}
onBlur={formik.handleBlur}
value={formik.values.dob}
format="yyyy-MM-dd"
error={formik.errors.dob && formik.touched.dob}
/>
</LocalizationProvider>

I can't get new value from autocomplete react

I am using autocomplete of material UI in my react app, I want to get the value when I change the item but I am getting undefined.
Here is my code
<Controller
name="partnerId"
control={control}
defaultValue={[]}
render={({ field: { onChange, value } }) => (
<Autocomplete
id="filter-demo"
className="mt-8 mb-16"
defaultValue={personObj}
value={value}
onChange={(newValue) => {
console.log('value...', newValue)
onChange(newValue);
}}
variant="outlined"
options={partners}
getOptionLabel={option => option.name}
filterOptions={filterOptions}
renderInput={params => <TextField {...params} label="Partners" variant="outlined" />}
/>
)}
/>
Try onchange as
onChange={(event,newValue) => {
console.log('value...', newValue)
onChange(newValue);
}}

React Material UI + Formik FieldArray Autocomplete control value stays same on remove

I want use Formik's form validation and it actually works just fine, but I ran into some issues with selected value display in Autocomplete component. I Have created Add/Remove buttons to dynamically adjust how many rows are in my form. The bug occurs when I try to remove form row, the row below, behind scenes has proper values as displayed in DEBUG, but user's input displays value from deleted form row. I cannot figure out, how to display or handle this occurrence.
Form before removal,
Form after removal
<FieldArray name="actions"
render={arrayHelpers =>
values.actions.map((action, index) => (
<Grid item container spacing={1} justify="center" alignItems="center"
key={index}>
<Grid item xs={4}>
<Field
error={getIn(errors, `actions.${index}.suggestedAction`) &&
getIn(touched, `actions.${index}.suggestedAction`)}
helperText={<ErrorMessage
name={`actions.${index}.suggestedAction`}/>}
name={`actions.${index}.suggestedAction`}
id={`actions.${index}.suggestedAction`}
variant="outlined"
fullWidth
as={TextField}
label="Siūloma priemonė"
multiline
rows={3}
rowsMax={10}
/>
</Grid>
<Grid item xs={4}>
<Autocomplete
freeSolo
onBlur={handleBlur}
onChange={(e, value) => {
//If adding new
if (value && value.inputValue) {
setOpen(true);
setFieldValue(`actions.${index}.responsiblePerson`, value.inputValue)
} else if (value && value.id) {
//Selecting existing
setFieldValue(`actions.${index}.responsiblePerson`, value.id)
} else {
setFieldValue(`actions.${index}.responsiblePerson`, "")
}
}}
getOptionLabel={(option) => {
if (typeof option === 'string') {
return option;
}
if (option.inputValue) {
return option.inputValue;
}
return option.title;
}}
handleHomeEndKeys
clearText="Pašalinti"
noOptionsText="Tuščia..."
renderOption={option => option.title}
filterOptions={(options, params) => {
const filtered = filter(options, params);
if (params.inputValue !== '') {
filtered.push({
inputValue: params.inputValue,
title: `Pridėti "${params.inputValue}"`,
});
}
return filtered;
}}
renderInput={params => (
<TextField
{...params}
id={`actions.${index}.responsiblePerson`}
name={`actions.${index}.responsiblePerson`}
error={getIn(errors, `actions.${index}.responsiblePerson`) &&
getIn(touched, `actions.${index}.responsiblePerson`)}
helperText={<ErrorMessage
name={`actions.${index}.responsiblePerson`}/>}
onChange={handleChange}
variant="outlined"
label="Atsakingas asmuo"
placeholder="Vardenis Pavardenis"
/>
)}
options={top100Films}/>
</Grid>
<DateTimeUtilsProvider>
<Grid item xs={3}>
<Field
disableToolbar
as={KeyboardDatePicker}
variant="inline"
inputVariant="outlined"
format="yyyy-MM-dd"
id={`actions.${index}.deadline`}
name={`actions.${index}.deadline`}
error={getIn(errors, `actions.${index}.deadline`) &&
getIn(touched, `actions.${index}.deadline`)}
helperText={<ErrorMessage
name={`actions.${index}.deadline`}/>}
label="Įvykdymo terminas"
onChange={value =>
setFieldValue(`actions.${index}.deadline`, value)}
/>
</Grid>
</DateTimeUtilsProvider>
<Grid item xs={1}>
<ButtonGroup fullWidth orientation="vertical" size="medium">
<Button onClick={() => {
arrayHelpers.remove(index);
}}
disabled={values.actions.length === 1}
classes={removeButtonClasses}>
<HighlightOff/>
</Button>
<Button onClick={() => {
arrayHelpers.insert(index + 1, {
suggestedAction: "",
responsiblePerson: "",
deadline: Date.now()
})
}}
color="primary">
<AddCircleOutline/>
</Button>
</ButtonGroup>
</Grid>
</Grid>
))
}
/>
</Grid>
Instead of
arrayHelpers.insert()
I have used
arrayHelpers.push()
and its working fine for me.
I had this same problem. I was setting a value prop on the <Field> inside my renderInput.
<Autocomplete
renderInput={params => (
<Field {...params} component={TextField} value={values.myArray[index]} />
)}
/>
I was able to fix it by moving the value attribute to the Autocomplete.
<Autocomplete
value={values.myArray[index]}
renderInput={params => (
<Field {...params} component={TextField} />
)}
...
/>
This worked for me
const arrayValue = options.filter(
(item) => item.id === values[arrayName][index][name]);
And then I used the filtered option as my value in the Autocomplete component
<Autocomplete
name={name}
value={arrayValue.length > 0 ? arrayValue[0] : null}
options={options}
groupBy={(option) => option.group}
getOptionLabel={(option) => option.value}
isOptionEqualToValue={(option, value) => option?.id === value?.id}
defaultValue={defaultValueCheck()}
onChange={(_, value) => {
setFieldValue(`${arrayName}[${index}].${name}`, value?.id ?? "");
}}
renderInput={(params) => (
<TextField
{...params}
{...configTextField}
name={`${arrayName}[${index}].${name}`}
/>
)}
renderGroup={(params) => (
<li key={params.key}>
<GroupHeader>{params.group}</GroupHeader>
<GroupItems>{params.children}</GroupItems>
</li>
)}
/>
</>

Resources