Material-table: Change colour on particular action onClick

Created on 10 Jul 2020  路  1Comment  路  Source: mbrn/material-table

How can I style a particular MT action based on a different state?

Currently I'm doing something like this:

 actions={[
              rowData => {
                const active = rowData && selected && rowData.tableData.id === selected.tableData.id;
                return {
                  icon: 'bug_report',
                  iconProps: { color: active ? 'secondary' : 'primary' },
                  onClick: (event, info) => {
                    setSelected(info);
                  },
                };
              },
]}

But instead of colouring the single element, it just stays primary and basically does nothing. Why? Because the actions is rendered for action row and the next row !== selected.

question

Most helpful comment

Hello, @tschaka1904!

I tried to figure out why 'iconProps' is not working in your example, but I failed :/. Probably we are missing something. Nevertheless, it's simple to solve your issue. You can set the icon props directly on the component as shown below.
(Code avaliable on CodeSand Box)

actions={[
  rowData => {
    const active = rowData && selected && rowData.tableData.id === selected.tableData.id;
    return {
      icon: () => <AddBox color={active ? 'secondary' : 'primary'} />,
      onClick: (event, info) => {
        setSelected(info);
      },
    };
  },
]}

action-color

>All comments

Hello, @tschaka1904!

I tried to figure out why 'iconProps' is not working in your example, but I failed :/. Probably we are missing something. Nevertheless, it's simple to solve your issue. You can set the icon props directly on the component as shown below.
(Code avaliable on CodeSand Box)

actions={[
  rowData => {
    const active = rowData && selected && rowData.tableData.id === selected.tableData.id;
    return {
      icon: () => <AddBox color={active ? 'secondary' : 'primary'} />,
      onClick: (event, info) => {
        setSelected(info);
      },
    };
  },
]}

action-color

Was this page helpful?
0 / 5 - 0 ratings