7

I´m doing some beginner practise on React.js and created a tree view component using material-ui. Now I want to implement a search bar to search for the entered keyword in the tree view. Here is my sample data:

[
    {
        id: 1,
        name: "Item 1",
        children: [
            {
                id: 2,
                name: "Subitem 1",
                children: [
                    {
                        id: 3,
                        name: "Misc 1",
                        children: [
                            {
                                id: 4,
                                name: "Misc 2"
                            }
                        ]
                    }
                ]
            },
            {
                id: 5,
                name: "Subitem 2",
                children: [
                    {
                        id: 6,
                        name: "Misc 3",
                    }
                ]
            }
        ]
    },
    {
        id: 7,
        name: "Item 2",
        children: [
            {   
                id: 8,
                name: "Subitem 1",
                children: [
                    {
                        id: 9,
                        name: "Misc 1"
                    }
                ]
            },
            {
                id: 10,
                name: "Subitem 2",
                children: [
                    {
                        id: 11,
                        name: "Misc 4"
                    },
                    {
                        id: 12,
                        name: "Misc 5"
                    },
                    {
                        id: 13,
                        name: "Misc 6",
                        children: [
                            {
                                id: 14,
                                name: "Misc 7"
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

The rendering part is working as expected.

const getTreeItemsFromData = treeItems => {
    return treeItems.map(treeItemData => {
        let children = undefined;
        if (treeItemData.children && treeItemData.children.length > 0) {
            children = getTreeItemsFromData(treeItemData.children);
        }
        return(
            <TreeItem
                key={treeItemData.id}
                nodeId={treeItemData.id}
                label={treeItemData.name}
                children={children}/>
        );
    });
};

const DataTreeView = ({ treeItems }) => {
    return(
        <TreeView
            defaultCollapseIcon={<ExpandMoreIcon />}
            defaultExpandIcon={<ChevronRightIcon />}
            >
            {getTreeItemsFromData(treeItems)}
        </TreeView>
    );
};

class App extends Component {
    render() {
        return (
            <div className="App">
               <DataTreeView treeItems={searchedNodes} />
            </div>
        );
    }
}

Now I´m struggeling to implement the search functionality. I want to use the material-search-bar (https://openbase.io/js/material-ui-search-bar)

1 Answer 1

8

This solution assumes that you use unique id for each item in the tree.

It uses Depth first search algorithm.

Before trying please fix your sample data non-unique IDs. I didn't notice them at first and wasted time debugging for no bug.

function dfs(node, term, foundIDS) {
  // Implement your search functionality
  let isMatching = node.name && node.name.indexOf(term) > -1;

  if (Array.isArray(node.children)) {
    node.children.forEach((child) => {
      const hasMatchingChild = dfs(child, term, foundIDS);
      isMatching = isMatching || hasMatchingChild;
    });
  }

  // We will add any item if it matches our search term or if it has a children that matches our term
  if (isMatching && node.id) {
    foundIDS.push(node.id);
  }

  return isMatching;
}

function filter(data, matchedIDS) {
  return data
    .filter((item) => matchedIDS.indexOf(item.id) > -1)
    .map((item) => ({
      ...item,
      children: item.children ? filter(item.children, matchedIDS) : [],
    }));
}

function search(term) {
  // We wrap data in an object to match the node shape
  const dataNode = {
    children: data,
  };

  const matchedIDS = [];
  // find all items IDs that matches our search (or their children does)
  dfs(dataNode, term, matchedIDS);

  // filter the original data so that only matching items (and their fathers if they have) are returned
  return filter(data, matchedIDS);
}
4
  • 2
    Hello Rashad, I´ve tried it and it´s working this way. Thank you!
    – stefano
    Apr 19, 2020 at 14:38
  • This is not a right solution. Children of "Subitem 1" array is missing in the output If you search by "Subitem 1" Jul 1, 2021 at 4:06
  • It is also working for me. But how to expand the node on search and collapse the node if search string is empty Oct 20, 2021 at 0:17
  • This may work but I find it very inefficient, especially for a large tree. You process the tree 3 separate times (one for initial React DOM creation, again to get node IDs, and finally to re-create the React DOM of TreeItems using the node IDs). Why not just filter when in getTreeItemsFromData()?
    – Greg Vogel
    Mar 9, 2022 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.