I am using Formik in my React project to process forms and using MUI UI components.
I am able to pick the day, month, but the year part does not change. If I manually type in year in the textfield, the year part is not reflected in the changed state.
Here's my code:
<LocalizationProvider dateAdapter={DateAdapter}>
<DatePicker
name="birthday"
id="birthday"
variant="standard"
label="Birthday"
value={formik.values.birthday}
renderInput={(params) => (
<TextField {...params} variant="standard" fullWidth/>
)}
onChange={(value) => formik.setFieldValue('birthday', value, true)}
error={formik.touched.birthday && Boolean(formik.errors.birthday)}
helperText={formik.touched.birthday && formik.errors.birthday}
/>
</LocalizationProvider>
The initial state:
const initialFormState = {
birthday: Date.now(),
};
All the other components are working correctly and changes in state show immediately.
The onChange property is not set in the DatePicker component. You have to move the onChange property from TextField to DatePicker.
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
onChange={(value) => setFieldValue("birthday", value, true)}
value={values.birthday}
renderInput={(params) => (
<TextField
error={Boolean(touched.birthday && errors.birthday)}
helperText={touched.birthday && errors.birthday}
label="Birthday"
margin="normal"
name="birthday"
variant="standard"
fullWidth
{...params}
/>
)}
/>
</LocalizationProvider>
Also, the name, id, variant and label are TextField's properties.
Here is the working CodeSandbox link.
Related
I am trying to block invalid date input by using the acceptRegex property in Datepicker but couldn't get it applied. I don't want the user to enter an invalid date like 3022-56-45 by keyboard input.I should be allowing the numbers which forms valid date only. Here is my current implementation.
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DesktopDatePicker
label="Date of Birth"
inputFormat="yyyy-MM-dd"
acceptRegex="/^d{4}-d{2}-d{2}$/"
mask={"____-__-__"}
minDate="1900-01-01"
value={dateOfBirth ? parseISO(dateOfBirth) : null}
onChange={(val) => {
setDateOfBirth(moment(val).utc().format("YYYY-MM-DD"));
}}
renderInput={(params) => (
<TextField fullWidth sx={{ pr: 3 }} {...params} />
)}
/>
</LocalizationProvider>
I am using datepicker from "#mui/x-date-pickers/DatePicker".
import { DatePicker } from "#mui/x-date-pickers/DatePicker";
import { AdapterMoment } from "#mui/x-date-pickers/AdapterMoment";
import { LocalizationProvider } from "#mui/x-date-pickers/LocalizationProvider";
<LocalizationProvider dateAdapter={AdapterMoment}>
<DatePicker
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
The dates and the weekdays should be in a straight line column
The columns are not in straight line
Did I accidentally overwrite the CSS somewhere?
I ran into a similar issue with the styling of the calendar icon (DatePicker Icon Button). I was able to modify it by following the suggestions in this post: How to change the icon in MUI DatePicker?
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker
OpenPickerButtonProps={{ style: { marginRight: 2 } }}
openTo="year"
views={['year', 'month', 'day']}
label="Date"
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(params) => <TextField {...params} helperText={null} />}
/>
</LocalizationProvider>
I'm using Material UI version 4 (the latest), and the Informed form library. I have a custom component (custom to integrate with Informed) that wraps the Material UI TextField which I'm rendering using the Autocomplete component.
App component
<Form getApi={(api) => setFormApi(api)}>
{formApi && (
<>
<label>
First name:
<Autocomplete
freeSolo
options={autoOptions}
renderInput={(params) => (
<CustomTextField field="name" {...params} />
)}
/>
</label>
<button type="submit">Submit</button>
<button type="button" onClick={() => formApi.reset()}>
Reset
</button>
<FormState />
</>
)}
</Form>
The issue
When the reset button is clicked you can see the Informed "form state" is cleared, but the input still has a value. Any ideas on how to solve this?
Example - Codesandbox
The inputProps are getting overriden by the ones provided by Autocomplete component, change the order you pass ...rest props and included the ...rest.inputProps in your custom inputProps with the correct value
<TextField
{...rest} // should go first to allow overriding
// only add value props for select fields
// value={value}
onChange={(event) => {
setValue(event.target.value);
if (onChange) {
onChange(event);
}
}}
onBlur={(event) => {
setTouched(true);
if (onBlur) {
onBlur(event);
}
}}
error={!!error}
helperText={error ? error : helperText ? helperText : false}
variant="outlined"
margin="none"
fullWidth
inputProps={{
...rest.inputProps, // must include otherwise it breaks
value:
!select && !maskedValue && maskedValue !== 0 ? "" : maskedValue,
maxLength: maxLength || undefined
}}
// eslint-disable-next-line
InputProps={{
style: sensitive && {
color: "rgba(0,0,0,0)",
caretColor: "#000"
},
startAdornment
}}
InputLabelProps={{
shrink: true
}}
autoComplete="off"
disabled={disabled}
/>
Could you please tell why my required check is not working in autocomplete .I am using material UI with react hook form.
Step to reproduce
Click Submit button it show field is required.
then select any element from list.
remove the selected element Then click again submit button.It should
show “required” field check.but it is not showing anything why ??
Here is my code
https://codesandbox.io/s/mui-autocomplete-with-react-hook-form-0wvpq
<Controller
as={
<Autocomplete
id="country-select-demo"
multiple
style={{ width: 300 }}
options={countries}
classes={{
option: classes.option
}}
autoHighlight
getOptionLabel={option => option.label}
renderOption={(option, { selected }) => (
<React.Fragment>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 8 }}
checked={selected}
/>
{option.label} ({option.code}) +{option.phone}
</React.Fragment>
)}
renderInput={params => (
<TextField
{...params}
label="Choose a country"
variant="outlined"
fullWidth
name="country"
inputRef={register({ required: true })}
// required
error={errors["country"] ? true : false}
inputProps={{
...params.inputProps,
autoComplete: "disabled" // disable autocomplete and autofill
}}
/>
)}
/>
}
onChange={([event, data]) => {
return data;
}}
name="country"
control={control}
/>
When the form loads initially, the value of your form is an empty object -
{}
When you select a country (say, 'Andorra') the value of your form becomes:
{"country":[{"code":"AD","label":"Andorra","phone":"376"}]}
And then when you deselect the country, the value of your form becomes:
{"country":[]}
An empty array technically meets the "required" criteria (it's not null, after all) so your required handler doesn't fire.
You can verify this is happening by showing the value of the form in your App class -
const { control, handleSubmit, errors, register, getValues } = useForm({});
return (
<form noValidate onSubmit={handleSubmit(data => console.log(data))}>
<Countries control={control} errors={errors} register={register} />
<Button variant="contained" color="primary" type="submit">
Submit
</Button>
<code>{JSON.stringify(getValues())}</code>
</form>
);
The simple fix is to NOT return an empty array as a value from your control - update your onChange handler as follows -
onChange={([event, data]) => {
return data && data.length ? data : undefined;
}}
I am trying to implement the Autocomplete component into my project but am getting the autofill/autocomplete from the browser after some time. Do you know how I can set it to off ?
<Autocomplete
id="combo-box-demo"
options={battleRepos}
getOptionLabel={option => option.full_name}
style={{ width: 500 }}
renderInput={params => (
<TextField {...params}
label="Combo box"
variant="outlined"
onBlur={event => console.log(event.target.value)}
fullWidth />
)}
/>
UPDATE
With the release of #material-ui/core 4.7.0 and #material-ui/lab 4.0.0-alpha.33, this is now fixed and no longer requires the workaround shown below.
This has been fixed in a recent pull request, but is not yet released (will be in the next release).
If you want to work around this prior to it being released (which will likely be within a few days), you can set inputProps.autoComplete = "off" like in the following:
<Autocomplete
id="combo-box-demo"
options={battleRepos}
getOptionLabel={option => option.full_name}
style={{ width: 500 }}
renderInput={params => {
const inputProps = params.inputProps;
inputProps.autoComplete = "off";
return (
<TextField
{...params}
inputProps={inputProps}
label="Combo box"
variant="outlined"
onBlur={event => console.log(event.target.value)}
fullWidth
/>
);
}
}
/>
Even with the latest:
"#material-ui/core"
"#material-ui/lab"
which contains the autoComplete property set to 'off', I wasn't able to get the autofill box go away.
Also tried setting the attribute on the form tag <form autoComplete="off">...</form>
To no avail.
The thing which resolved the issue was setting the autoComplete field to 'new-password'
<Autocomplete
id='id'
options={data}
onChange={(e, val) => input.onChange(val)}
renderInput={(params) => {
params.inputProps.autoComplete = 'new-password';
return <TextField {...params}
label={label} placeholder="Type to Search" />
}}
/>