Enzo Dtz
Enzo Dtz

Reputation: 381

Edit material UI style programatically

I'm trying to make an input expand when I press the search button, but I can't change the material-ui style after using makeStyles.

Is there a way I can do it?

Thanks

Sample code:

const useStyles = makeStyles((theme) => ({
  searchInput: {
    width: 0,
    padding: 0,
    border: "none",
  },
}));

function ExpandableSearchBar() {
  const classes = useStyles();

  function onClick() {
   // change style of the input class
   // classes.searchInput
  }

  return (
    <div className="component-wrapper">
      <IconButton onClick={onClick} aria-label="Search">
        <SearchIcon />
      </IconButton>
      <input className={classes.searchInput} type="text" />
    </div>
  );
}

Upvotes: 0

Views: 28

Answers (1)

bonnopc
bonnopc

Reputation: 850

You can set a state to toggle className of the input. Your code should look like -

const useStyles = makeStyles((theme) => ({
  searchInput: {
    width: 0,
    padding: 0,
    border: "none",
  },
  expandedSearchInput: {
    width: "5rem" // or, you can set it as per your need
    // add other styles of expanded input
  }
}));

function ExpandableSearchBar() {
  const [isExpanded,setExpand] = useState(false);
  const classes = useStyles();

  function toggleSearchInput(){
    setExpand(val => !val);
  }

  return (
    <div className="component-wrapper">
      <IconButton onClick={toggleSearchInput} aria-label="Search">
        <SearchIcon />
      </IconButton>
      <input 
        className={isExpanded ? classes.expandedSearchInput : classes.searchInput} 
        type="text" /> 
    </div>
  );
}

Note - Have a look on the className of the <input/>. It will change to classes.expandedSearchInput when the isExpanded is set to true.

Upvotes: 1

Related Questions