Search code examples
javascriptreactjssearchantd

Antd Tree search is not expanding sublist children when searching with a value


Antd Tree search is not expanding sublist children when searching with a value, it is working fine with list and sublist but not with the sublist children.

Below is the sandbox link

https://codesandbox.io/s/controlled-tree-antd-4-19-1-forked-3h6fne

When I search I get like below, where there is search find under Data List Tree but it is not expanding

enter image description here

I am expecting it to come like below, It should also expand Data List tree as there is a search find under it. and eliminate remaining children which are not matching with the search key.

It is not opening sub-lists after searching

enter image description here

Finally, I need like below, after eliminating the un-matching values enter image description here

Can Someone help me in this?


Solution

  • Below are the changes for the answer, where Data List tree expanded as there is a search find under it. and eliminate remaining children which are not matching with the search key. Hope this helps someone :)

    Referred below link and it worked with all scenarios root level,sub root and final children search

    I find this post : filter nested tree object without losing structure How filter in a nested tree object without losing structure in javascript?

    function searchFilter(array, name) {
      return array.reduce((r, { children = [], ...o }) => {
        if (hasSearchTerm(o.title, name)) {
          if (children) {
            r.push(Object.assign(o, { children }));
            return r;
          } else {
            r.push(o)
            return r;
          }
        }
        children = searchFilter(children, name);
        if (children.length) {
          r.push(Object.assign(o, { children }));
        }
        return r;
      }, []);
    }
    

    Attaching Codesanbox link : https://codesandbox.io/s/controlled-tree-antd-4-19-1-forked-3h6fne?file=/index.js