Search code examples
reactjsmaterial-uimui-datatable

How can I prevent the onRowClick when an action button from custombodyrender is clicked?


I'm using a mui-datatable where the onRowClick will direct the user to another page. I also have custom action button in each row. However, If i'll click the custom action button, it will also trigger the onRowClick which will direct the user to another page. How can I prevent the onRowClick when clicking the custom action button?

class orders extends Component {
  constructor() {
    super();
    this.state = { orders: [] };
  }

  handleRowClick = (rowData, rowMeta) => {
    this.props.history.push("/details", `${rowData[0]}`);
  };

  columns = [
    "Order ID",
    "Items",
    "Address",
    "Total Amount",
    {
      name: "Action Button",
      options: {
        filter: true,
        sort: false,
        empty: true,
        customBodyRender: (value, tableMeta) => {
          return (
            <FormControlLabel
              value={value}
              control={
                <Button
                  value={value}                >
                  Action Button
                </Button>
              }
              onClick={(e) => {
                //firestore codes
              }}
            />
          );
        },
      },
    },
  ];
  options = {
    onRowClick: this.handleRowClick,
  };

  render() {
    return this.state.orders ? (
      <div>
        <MUIDataTable
          title={" Orders"}
          columns={this.columns}
          data={this.state.orders}
          options={this.options}
        />
        
      </div>
    ) : (
      <p>Loading...</p>
    );
  }
}
export default withRouter(orders);

Solution

  • Assuming you have a button

    <button onClick={onClick} >Don't Bubble</button>
    

    You may use event.stopPropagation() to prevent event from bubbling up to parent.

    const onClick=(event) => {
        event.stopPropagation()
    
        .. do what u want with the button
    }