Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MaterialUI ButtonGroup - Active

Tags:

material-ui

So I understand that I can do a button group like this, which is great.

However how can I make it so that when say button one is pressed that it looks like it as been selected? As all this does is a click effect?

Basically what I want to do is when a button is clicked it changes an input value to the value of the button. But I would like the button to look like it was selected.

    <ButtonGroup disableElevation variant="contained" color="primary">
      <Button>One</Button>
      <Button>Two</Button>
    </ButtonGroup>
like image 229
RussellHarrower Avatar asked Dec 13 '22 08:12

RussellHarrower


2 Answers

I'd use state to keep track of the selected Button and utilize the color prop to assign the color. For arbitrary color, you can use the MUI ThemeProvider or makeStyles

function App() {

  const [selectedBtn, setSelectedBtn] = React.useState(-1);
 
  return(
    <div>
      <ButtonGroup disableElevation variant="contained" color="primary">
        <Button color={selectedBtn === 1 ? "secondary" : "primary"} onClick={()=>setSelectedBtn(1)}>One</Button>
        <Button color={selectedBtn === 2 ? "secondary" : "primary"} onClick={()=>setSelectedBtn(2)}>Two</Button>
      </ButtonGroup>
    </div>
  );
}

ReactDOM.render(<App/>, document.getElementById("root"));
<body>
  <div id="root"></div>

  <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  <script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>
  <script type="text/babel">
    const { ButtonGroup, Button } = MaterialUI;
  </script>
</body>
like image 81
95faf8e76605e973 Avatar answered May 22 '23 19:05

95faf8e76605e973


You can use Toggle Buttons - https://material-ui.com/components/toggle-button.

Combine that with the ToggleButtonGroup API and you should be good to go - https://material-ui.com/api/toggle-button-group/#togglebuttongroup-api.

like image 30
Vignesh Chandrasekharan Avatar answered May 22 '23 19:05

Vignesh Chandrasekharan