naisutech/react-tree

research is possible?

paulopelaez opened this issue · 3 comments

is there any possibility of including a search possibility?

I need to pass a string and it shows only parents and children that contain those characters, is it possible?

@paulopelaez -- it's out of the scope of this library. You can you achieve the same by wrapping the tree and an input in another component and just filtering the list of nodes to the tree:

const [searchTerm, setSearchTerm] = React.useState(null)
const filterNodes = nodes => nodes.filter(n => searchTerm ? n.label.contains(searchTerm) : true)

// other component code
<Tree nodes={filterNodes} />

@ortonomy this would not work right?
because it would filter out parent nodes that are required for rendering the matching labeled children?

Tree

  • apple
    • watermelon
  • banana

If we search for watermelon, and use the filtering logic suggested, apple would be filtered breaking the rendering of watermelon, right?

in my case, i only needed to filter on the leaf nodes.
so before converting my items into react-tree Nodes, i filtered the raw items first.

something like..

const [searchText, setSearchText] = useState<string | undefined>(undefined);
...
const filteredItems = searchText ?
      items.filter(n => {
          return n.displayName?.toLocaleLowerCase().includes(searchText);
      }) :
      items;
...
const nodes: NodeList = [];

if (parentNode) {
    nodes.push({
        id: carCategory?.categoryId.toString(),
        label: carCategory?.displayName,
        parentId: null,
        items: filteredEntities
             // only add items if related
            .filter(e => e.parentId === parentNode.id)
            .map(e => ({ id: e.itemId, label: e.displayName, parentId: e.parentid }))
    })
}

which yielded the desired result.

so overall, filter you data first before converting it into react-tree Node.