[SalesForce] LWC Tree Grid – Displaying actions conditionally

I've created a tree grid LWC component that includes few actions.
Is there a way to display actions depending on a certain value of the record/row?

For example, let us say I'm displaying users and I want to have a specific action for inactive users, is that possible? I didn't find anything on the documentation.

Thanks!

Best Answer

Yes, that is possible.

The actions work pretty much the same in both Lightning Datatable and Tree Grid, in the Tree Grid Documentation its mentioned to refer to the Lightning Datatable documents for Actions.

See how row actions are set using a method getRowActions. In the below example, actions are rendered on the basis of isActive field.

import { LightningElement } from 'lwc';

const actions = [
    { label: 'Show details', name: 'show_details' },
    { label: 'Delete', name: 'delete' }
];

const columns = [
    // Your column data
];

export default class DatatableExample extends LightningElement {
    data = [];
    columns = columns;

    constructor() {
        super();
        this.columns = [
            // Other column data here
            { type: 'action', typeAttributes: { rowActions: this.getRowActions } },
        ]
    }

    getRowActions(row, doneCallback) {
        const actions = [];
            if (row['isActive']) {
                actions.push({
                    'label': 'Deactivate',
                    'iconName': 'utility:block_visitor',
                    'name': 'deactivate'
                });
            } else {
                actions.push({
                    'label': 'Activate',
                    'iconName': 'utility:adduser',
                    'name': 'activate'
                });
            }
            // simulate a trip to the server
            setTimeout(() => {
                doneCallback(actions);
            }), 200);
    }
}

You can refer to this article (search for "Creating Dynamic Row-Level Actions") mentioning how to do that in detail.

Related Topic