How can I clear MUI DatePicker input? - reactjs

I would like to add a 'clear' button to a DatePicker from #mui/lab (5.0.0-alpha.55).
What I am attempting:
Store a date field in state, passed as the value prop to DatePicker
Change the date to null when desired to 'clear' the value & input
The behaviour I observe:
If the date is valid, it works as expected, and the input is cleared
If the date is not valid, the error is cleared, but the invalid date still stays in the input.
The rudimentary version I have attempted which shows the behaviour above can be seen here.
If you input a partial date, then click clear, you can observe that the input does not get cleared.
I would prefer to avoid a solution that involves changing the key, as that brings other issues, such as not respecting an external source changing the date to null, and needing additional hacks to respect the label transition when clearing the input.

My theory is that internally, DatePicker only updates the input value if it's different with the last valid value. Below is how the bug can occur:
You clear the DatePicker when there is a valid value (like the initial Date), the state is reset successfully at first (value=null, inputValue='')
You enter some invalid date. The state is now (value=Invalid Date, inputValue='invalid Text')
Because the current value is invalid, it does not count and the DatePicker references the last valid value instead which is null, then decide that the current value doesn't change and skip dispatching the new input value (value=null, inputValue='invalid Text').
I'd classify this as a bug from MUI, you can create an issue on github if you want it to be fixed. In the meanwhile, you can fix the bug by applying this patch using patch-package:
Install patch-package: npm i patch-package
Add postinstall script in the package.json
"scripts": {
"postinstall": "patch-package"
}
Open the buggy file at node_modules\#mui\lab\internal\pickers\hooks\useMaskedInput.js and change it based on this commit.
Run npx patch-package #mui/lab to create the patch that will be applied every time after you ran npm i #mui/lab again.
Restart your dev server.

As of today you could do:
<DatePicker
componentsProps={{
actionBar: {
actions: ['clear'],
},
}}
onAccept={(newDate) => {
console.log(newDate);
}}
/>
and see if newDate is null.

MUI DatePicker has a clearable property. When set to true, it shows a clear button. You can change the text of the clear button using the clearText property.
I would point out however, that it does not trigger an onChange event, nor is there an onClear event (at the time of writing this post). So when I am using it, its not possible to change the state that way. However the onAccept event is fired, and if you pass the value parameter, it will be null.
<MobileDatePicker
open
clearable
label="some label"
inputFormat="yyyy-MM-dd"
value={stateDate}
onChange={(date) => updateAvailableDate(date)}
renderInput={(params) => (
<TextField
{...params}
/>
)}
onClose={() => hideModal()}
clearText="Clear me"
onAccept={(value) => handleSave(value)}
/>
See all the api settings here.
https://mui.com/api/date-picker/

how about this custom component?.
const DatePickerClear = (props) => {
const { onClear } = props;
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
{...props}
renderInput={(params) => (
<div style={{ position: "relative", display: "inline-block" }} >
<TextField {...params} />
{props.value &&
<IconButton style={{ position: "absolute", top: ".5rem", margin: "auto", right: "2rem" }} onClick={() => onClear()}>
<ClearIcon />
</IconButton>
}
</div>
)
}
/></LocalizationProvider >
)
}
export default DatePickerClear
I give you too a github basic project in react.
https://github.com/HastaCs/MUI_DatePicker_ClearButton

This is what I did to make the clear function work. I recently found this solution so I might change this in the future... but for now it's fine.
<MobileDateTimePicker
...
clearable
clearText="Clear"
onChange={(newScheduleDateTime) => {
if (newScheduleDateTime) {
setScheduleDateTime(newScheduleDateTime);
} else {
setScheduleDateTime(null);
}
}}
/>

Related

Is there a way to clear a MUI TextField Input from the form.restart() method in React-Final-Form and capture the event?

The form.restart() in my reset button resets all fields states and values as per my understanding of this Final-Form.
The method fires and resets all fields in my form and I can capture the event in the autocomplete, but I am unable to capture the clear event in the textfield - I have a state (not related to the value of the field) I need tor reset.
My form reset button
<Button
type={"button"}
disabled={submitting || pristine}
variant={"outlined"}
onClick={() => {
form.getRegisteredFields().forEach((field) => form.resetFieldState(field));
form.restart();
if (clearActionHandler) {
clearActionHandler();
}
setFormSubmittedOnce(false);
}}
>
Clear
</Button>;
My textfieldadapter
const [shrink, setShrink] = useState < boolean > false;
const countCharacters: (
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
) => boolean = (e) => {
setCount(e.target.value.length);
return maxCharacterCount === 0 || e.target.value.length < maxCharacterCount;
};
return (
<TextField
{...input}
{...rest}
onChange={(e) => {
if (countCharacters(e)) {
input.onChange(e);
}
}}
value={input.value}
onBlur={(e) => {
!input.value && input.onBlur(e);
!input.value && setShrink(false);
}}
error={meta.error && meta.touched}
helperText={
meta.touched ? (
<React.Fragment>
{maxCharacterCount > 0 ? (
<React.Fragment>
<Typography variant={"body1"} textAlign={"end"}>
{count}/{maxCharacterCount}
</Typography>
<br />
</React.Fragment>
) : null}{" "}
{meta.error}
</React.Fragment>
) : maxCharacterCount > 0 ? (
<React.Fragment>
<Typography variant={"body1"} textAlign={"end"}>
{count}/{maxCharacterCount}
</Typography>
<br />
</React.Fragment>
) : (
""
)
}
placeholder={placeholder}
fullWidth={true}
margin={"dense"}
multiline={multiline > 1}
rows={multiline}
inputProps={inputProps}
InputProps={{
startAdornment: (
<InputAdornment position={"start"} sx={{ width: "24px" }}>
{startAdornment}
</InputAdornment>
),
}}
InputLabelProps={{
shrink: shrink,
}}
onFocus={() => setShrink(true)}
sx={{
"& .MuiInputLabel-root:not(.MuiInputLabel-shrink)": {
transform: "translate(50px, 17px)",
},
}}
/>
);
Versions of packages:
"#mui/material": "^5.11.1",
"react": "^18.2.0",
"react-final-form": "^6.5.9"
I have tried to capture the onChange event with bluring all elements before the reset method is called, that doesn't call the textfield onblur method. I am just not sure how to clear it away.
Make sure that the field in question has an entry in initialValues and that that entry is initialised to an empty string. This is a long shot, so take everything I say as theory, but it looks like what would happen if the initial value was not defined or was explicitly set to undefined.
That would mean when you reset the form, the value prop of the TextField would be set to undefined. This is not a valid controlled value of a TextField, so the behavior of MUI could well be to switch to uncontrolled mode, where the value is kept internally and not actually controlled by the value prop anymore. It depends on the library what happens next as this is generally unexpected and leads to non-deterministic behavior, but it's likely that MUI just keeps the previous controlled value around internally, or it's sitting in a transient DOM state on the element itself since value is judged to be no longer the source of truth and so it was never written to the actual DOM element. When the user types again, onChange would be called, the state in your form set to a string, and it would become controlled again. Base react <input> gives warnings in the console when you transition like this but MUI might not.
This might explain why it does not capture the transition to the original form state.
Note null is usually not allowed either but there's some final form magic that protects you from that one.
I verified MUI does this on a codesandbox (excuse the old class style I just used an old TextField sandbox to build on). If my long shot is correct, the problem is more related to a core issue between your state consistency and the mui lib and less about final form.
The fix would be to make sure the field has an entry in initialValues set to a string. You could optionally put in guards to check for undefined and use '' instead when that's the case.
Take note that '' is actually still falsey so !input.value would evaluate to true when its empty string still. Not sure you care, but something to keep in mind.

MUI & Formik: Validation doesn't trigger for useField

Codesandbox with minimal working example: https://codesandbox.io/s/mystifying-lake-m0oxc?file=/src/DemoForm.tsx
Essentially, I have a AutoComplete dropdown which is tied into a Formik form with the useField hook. This sets the value correctly on any change, but the validation doesn't seem to trigger when I expect it to.
Validation runs successfully and removes the error if:
Another field is changed
I click on the "background" after selecting a value in the dropdown
What I expected and wanted was that the validation should run immediately when a value is selected.
To reproduce:
Click the category dropdown
Select a value, which closes the dropdown
Confirm that the error is still indicated (on the field and in the printout)
Click elsewhere on the screen. This should trigger validation and clear the error.
Any suggestions?
Edit:
I've tested an equivalent implementation with react-select as the dropdown and had the same issue, so I don't think it's directly tied to MUI.
I just reproduced based on the working example what you provided and realized that you set helpers.setTouched manually.
Just don't overuse the setTouched and also you need to handle if you remove the selected item from the autocomplete.
<Autocomplete
disablePortal
id="category-selector"
options={options}
onBlur={() => helpers.setTouched(true, true)}
isOptionEqualToValue={(option, value) => option.id === value.id}
onOpen={() => helpers.setTouched(true, true)}
onChange={(_, option) => {
if (option) {
helpers.setValue(option.id);
} else {
helpers.setValue(0);
}
}}
renderInput={(params) => (
<TextField
{...params}
label="Category"
error={meta.touched && Boolean(meta.error)}
/>
)}
/>

Using onSelect property of materialUI autocomplete form

I'm trying to create a search form with autocomplete suggestions that pulls data from API. I got everything to work in terms of displaying data and selection, but I would like to automatically take the user to the related page once they select one of the suggestions.
<Autocomplete
id="search-input"
freeSolo
disableClearable
options={playerList}
getOptionLabel={(option) => option.nickname}
style={{ width: 200}}
**onClick={console.log("you clicked")}
onSelect={(val)=> window.location.href = "/player-statistics/"+val.nickname+"-"+val.account_id+"-"+server}**
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
if (newInputValue.length >= 3) {fetchPlayers(newInputValue)}
}}
renderInput={(params) => <TextField {...params} label="Search Players" variant="outlined" margin="normal" />}
/>
I have tried with onChange and onSelect, but they are both reloading the page continuously whenever you press the search field or start typing.
The idea is to skip the need to click "search" button.
When you select a suggested name, onInputChange is triggered.
There you need to put the logic for changing the location.
Then the user does not have to click anything else.
If you do not want the page to change when the user only types a single character,
then you need to write logic for that inside onInputChange.
sth. like
// inside onInputChange
if(isASuggestedName(newInputValue)) {
//...change location
}
I figured it out after going through the API.
onChange call has 3 parameters - function(event: object, value: T | T[], reason: string) => void
I basically set it up so relocation is triggered only if reason is select-option and it works perfectly.
Thank you everyone

How to I keep a Material-ui Select open when I click on only one of the items in it

I have been writing a custom Material-UI Select dropdown which has an optional text field at the top to allow the user to search / filter items in the Select if there were many entries.
I am struggling with how to keep the Select open when I click on the text field (rendered as an InputBase) and just have the normal behavior (of closing the Select when a regular MenuItem is selected.
CodeSandbox here : https://codesandbox.io/s/inspiring-newton-9qsyf
const searchField: TextField = props.searchable ? (
<InputBase
className={styles.searchBar}
onClick={(event: Event) => {
event.stopPropagation();
event.preventDefault();
}}
endAdornment={
<InputAdornment position="end">
<Search />
</InputAdornment>
}
/>
) : null;
return (
<FormControl>
<Select
className={styles.root}
input={<InputBase onClick={(): void => setIconOpen(!iconOpen)} />}
onBlur={(): void => setIconOpen(false)}
IconComponent={iconOpen ? ExpandMore : ExpandLess}
{...props}
>
{searchField}
{dropdownElements.map(
(currEntry: string): HTMLOptionElement => (
<MenuItem key={currEntry} value={currEntry}>
{currEntry}
</MenuItem>
)
)}
</Select>
</FormControl>
);
As you can see above I've tried using stopPropagation and preventDefault but to no avail.
check out this codesandbox link: https://codesandbox.io/s/busy-paper-9pdnu
You can use open prop of Select API
I was able to make a controlled open select by providing open prop as a react state variable and implementing correct event handlers. To make it controlled you must provide onOpen and onClose props of the Select and make sure the open prop stays true when the custom textfield is clicked.
One more important thing I had to do was override the default keyDown behavior of the Select component. If you open up a Select and start typing into it, it shifts focus to the select option that matches what you are typing. For example, if you Select had an option with the text Foobar and if you start typing Food and water, it would cause focus to shift from your custom text input onto the Foobar option. This behavior is overridden in the onKeyDown handler of the custom textfield
Working sandbox here
Edit: even though this worked in the codepen, I had to add onChange={handleOpen} to the Select as well to get it working on a real browser with React and Next.
You can still use stopPropagation to make it work
// open state
const [isSelectorOpen, setisSelectorOpen] = useState(false)
// handle change
const handleChange = event => {
const { value } = event.target
event.stopPropagation()
// set your value
}
// selector
<Select
multiple
open={isSelectorOpen}
onChange={handleChange}
input={(
<Input
onClick={() => setisSelectorOpen(!isSelectorOpen)}
/>
)}
// other attribute
>
<MenuItem>a</MenuItem>
<MenuItem>b</MenuItem>
<MenuItem>c</MenuItem>
</Select>
In my case, none of the above worked, but this did the trick to stop closing the Select:
<MenuItem
onClickCapture={(e) => {
e.stopPropagation();
}}>
You can also change onMouseEnter to change some default styling that comes with using MenuItem (like pointer cursor when mouse enters its layout)
onMouseEnter={(e) => {
e.target.style.backgroundColor = "#ffffff";
e.target.style.cursor = "default";
}}
In my case i also needed to remove the grey clicking effect that MenuItem makes on click, which is a new object generated in MuiTouchRipple-root, so changing display to none did the trick.
sx={{
"& .MuiTouchRipple-root": {
display: "none",
},
}}

Adding ErrorText to material-ui Textfield moves other elements

I have a signup form in a React app. I am using material-ui TextField and use the errorText property to add a message if there is an error in the input.
errorText={this.state.messages.emailMessage}
The state.messages.emailMessage is initially set to null and so TextField does not have the extra space for the message when the input is first rendered.
When the message is added it moves the other elements.
How can I allow space for the new node if it is needed so that the other elements are not moved? I tried setting the initial state of the message to ' ' but this colours the input red for error and doesn't work anyway!
You could just use the errorStyle property setting an absolute position..
That's how I fix those problems in my projects.
In the end I passed a style parameter to the material-ul component that set the errorText to display: table. This then stopped it from affecting the other elements when it was added.
To where should this style added?
It needs to be added for the HelperText styles. Here is an example:
const helperStyles = makeStyles(theme => ({
root: {
position: 'absolute',
bottom: '1em',
},
}))
const helperClasses = helperStyles()
<FormHelperText classes={helperClasses}>
{helperText}
</FormHelperText>
You can make them a fixed height by making the helperText equal to an empty space when there is no message to show.
<TextField helperText={error ? error.message : ' '} />
Like #leonormes 's post suggests, adding the errorStyle prop to the material ui component and setting the display property to "table" solved this issue.
The material UI components no longer moves or becomes unaligned when showing an error.
Here's what the component ended up looking like:
<TextField
floatingLabelText="Name"
value={this.state.name}
onChange={e => this.setState({ name: e.target.value })}
errorText={this.props.validationErrors.get('name')}
errorStyle={{ display: "table" }}
/>
You can target the MuiFormHelperText-root class . Below example is when you are applying style inside MUI makeStyles , but you can do the same thing with external CSS file .
'& .MuiFormHelperText-root' : {
position : 'absolute',
bottom : '-1rem'
}
For those who need an updated answer (errorText isn't a thing anymore as far as I could tell), then hopefully this will work:
<Box style={{ minHeight: "100px" }} >
<TextField
{...props}
/>
</Box>
It allows the error text message to be rendered inside the flexbox without affecting the other components, so it shouldn't disturb the things around it.
CodeSandbox
You can do something like this
const useStyles = makeStyles({
helperText: {
'& .MuiFormHelperText-root': {
height: '0',
marginTop: '0'
}
}
});
And then add this class text field control
className={classes.helperText}
Just setting position to absolute didn't work at all. This enables error text to display on input field. So for perfect fix we also have to set bottom with some value to make it fixed. Example below.
errorStyle:{
position: 'absolute',
bottom: '-0.9rem'
}
As mentioned in other answer setting display to table worked as well.
So both the styles works

Resources