Below is an example that is roughly equivalent to what is being done in Autocomplete. The gist of the approach is to make the icon hidden by default, then flip the visibility to visible
on hover of the input (&:hover $clearIndicatorDirty
) and when the input is focused (& .Mui-focused
), but only if there is currently text in the input (clearIndicatorDirty
is only applied when value.length > 0
).
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import IconButton from "@material-ui/core/IconButton";
import ClearIcon from "@material-ui/icons/Clear";
import clsx from "clsx";
const useStyles = makeStyles(theme => ({
root: {
"&:hover $clearIndicatorDirty, & .Mui-focused $clearIndicatorDirty": {
visibility: "visible"
}
},
clearIndicatorDirty: {},
clearIndicator: {
visibility: "hidden"
}
}));
export default function CustomizedInputBase() {
const classes = useStyles();
const [value, setValue] = React.useState("");
return (
<TextField
variant="outlined"
className={classes.root}
value={value}
onChange={e => setValue(e.target.value)}
InputProps={{
endAdornment: (
<IconButton
className={clsx(classes.clearIndicator, {
[classes.clearIndicatorDirty]: value.length > 0
})}
size="small"
onClick={() => {
setValue("");
}}
>
<ClearIcon fontSize="small" />
</IconButton>
)
}}
/>
);
}
Related documentation: