1

We have a table component built in LWC. There is a button, on click of which the rows will be sorted based on some logic. All this markup is a part of the table component. This sorting function is also decorated with @api, so that we can execute this function from the parent (wrapper) component.

Now we are looking for a way so that we can override the sort logic that is already built inside the table component, and provide our own custom logic from the parent (wrapper) component. We really don't want to touch the table component.

This is something like the owner of the component has exposed few APIs to the outer world, and we have to implement these methods. Is this possible in LWC?

1
  • How about "search it in the wrapper component, then pass to the child?" May 28, 2020 at 10:21

1 Answer 1

1

When you invoke sort function of table which is a click function, you will get event property by default which is of type object. You can leverage this to pass in your own function because the type of function will be function.

handleSort method in table component js:

data = [ { name: 3 }, { name: 1 }, { name: 2 }, { name: 4 } ];
@api
handleSort(eventOrFunction) {
    if (typeof eventOrFunction === 'function') {
        console.log('handleSort function passed from wrapper');
        this.data.sort(eventOrFunction);
    } else {
        // default sort
        console.log('handleSort invoked in CHILD');
        this.data.sort((a, b) => {
            if (a.name > b.name) return 1;
            return -1;
        });
    }
    console.log('sorted data => ', JSON.stringify(this.data));
}

Now, you can pass your own function for sort from wrapper component:

sortChildData() {
    let parentSortFunc = (a, b) => {
        if (a.name > b.name) return -1;
        return 1;
    };
    this.template.querySelector('c-child').handleSort(parentSortFunc);
}

Here is the playground example

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .