Search code examples
reactjsmaterial-uibuttongroup

Increment and Decrement button via Material UI ButtonGroup


I want to create a increment / decrement button with material ui ButtonGroup. the button is like this image at first.

The first part of ButtonGroup

When user clicked on the button, the second part of ButtonGroup will show (Like Image Below).

Second part of the ButtonGroup

how can I achieve this? Please Help.

thanks in advance.

Code

import React from "react";
import Grid from "@material-ui/core/Grid";
import Button from "@material-ui/core/Button";
import ButtonGroup from "@material-ui/core/ButtonGroup";

class GroupedButtons extends React.Component {
  state = { counter: 0 };

  handleIncrement = () => {
    this.setState(state => ({ counter: state.counter + 1 }));
  };

  handleDecrement = () => {
    this.setState(state => ({ counter: state.counter - 1 }));
  };
  render() {
    const Btn = (
     <>
      <Button disabled>{this.state.counter}</Button>
      <Button onClick={this.handleDecrement}>-</Button>
     </>
    );

    return (
      <ButtonGroup size="small" aria-label="small outlined button group">
        <Button onClick={this.handleIncrement}>+</Button>
        {this.state.counter > 0 && Btn}
      </ButtonGroup>
    );
  }
}

export default GroupedButtons;

something like code above. but it doesn't work.


Solution

  • Material UI ButtonGroup expects only Button children. You pass React.Fragment as a child.

    You can change the code this way:

    import React from "react";
    import Button from "@material-ui/core/Button";
    import ButtonGroup from "@material-ui/core/ButtonGroup";
    
    class GroupedButtons extends React.Component {
      state = { counter: 0 };
    
      handleIncrement = () => {
        this.setState(state => ({ counter: state.counter + 1 }));
      };
    
      handleDecrement = () => {
        this.setState(state => ({ counter: state.counter - 1 }));
      };
      render() {
        const displayCounter = this.state.counter > 0;
    
        return (
          <ButtonGroup size="small" aria-label="small outlined button group">
            <Button onClick={this.handleIncrement}>+</Button>
            {displayCounter && <Button disabled>{this.state.counter}</Button>}
            {displayCounter && <Button onClick={this.handleDecrement}>-</Button>}
          </ButtonGroup>
        );
      }
    }
    
    export default GroupedButtons;
    

    See live demo here:

    Edit thirsty-rain-i1tzi