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>
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With