Material-UI: Make IconButton only visible on hover?
Asked Answered
R

1

6

I am making a custom input component with MUI InputBase, and I want to have a "Clear" button endAdornment that only appears when you hover over the input:

    <InputBase
      inputComponent={getCustomInputComponent()}
      onClick={onClick}
      ...
      endAdornment={
        <IconButton
          size='small'
          onClick={handleClear}>
          <IconClear fontSize='small'/>
        </IconButton>
      }
    />

Similar to how their new "Autocomplete" component works: https://material-ui.com/components/autocomplete/

I've looked at the source code of Autocomplete but I can't get it working in my component, any suggestions?

Resuscitate answered 4/12, 2019 at 21:14 Comment(0)
D
8

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>
        )
      }}
    />
  );
}

Edit Material demo

Related documentation:

Dissolve answered 4/12, 2019 at 21:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.