Skip to content

Modifying state in onNodeToggle breaks keyboard navigationΒ #18249

@apolakipso

Description

@apolakipso
  • The issue is present in the latest release.
  • I have searched the issues of this repository and believe that this is not a duplicate.

Current Behavior 😯

Pressing ↓ on an expanded node that has children throws the following error and does not select the first child node.

TreeView.js:129 Uncaught TypeError: Cannot read property '0' of undefined
    at getNextNode (TreeView.js:129)
    at focusNextNode (TreeView.js:180)
    at handleKeyDown (TreeItem.js:199)

Here's the part that breaks in node_modules\@material-ui\lab\TreeView\TreeView.js

  var getNextNode = function getNextNode(id, end) {
    var map = nodeMap.current[id];
    var parent = nodeMap.current[map.parent];

    if (!end) {
      if (isExpanded(id)) {
          
        // getNextNode (TreeView.js:129)
        // While the node has correctly been expanded, it does 
        // not have children at this point
        return map.children[0];
      }
    }

I only encountered the issue on the first node.

Workaround

Adding a hidden dummy item in first place enables properly expanding and navigating the first visible node and its children.

However, the user can still navigate up to the hidden node. They'll interact with the hidden dummy node while the first visible one (Applications) is still focused visually, but seemingly unresponsive.

Expected Behavior πŸ€”

Pressing ↓ on an expanded node that has children should select the first child element (Calendar).

Steps to Reproduce πŸ•Ή

https://codesandbox.io/s/material-ui-treeview-keyboard-navigation-bug-z138z

Steps:

  1. Click the first node Applicationsβ€”it's now focused and opened
  2. Press the down arrow key (to select the first child)β€”the child Calendar should get selected, instead nothing happens.

The sandbox has three trees: The first one exhibiting the issue, the second with the workaround described above, the third is the original example from the documentation with an event handler that does not modify state at all.

Context πŸ”¦

I'm trying to persist the state of opened tree items to restore the whole tree view.

I keep track of expanded nodes in state (adding/removing the respective node when onNodeToggle is called) and pass this array as defaultExpanded to the TreeView to rebuild the tree and have the correct nodes expanded.

Your Environment 🌎

The project is using a Parcel setup, but the issue can be reproduced in the simple create-react-app sandbox forked from the original example in the documentation (https://material-ui.com/components/tree-view/)

Tech Version
@material-ui/lab v4.0.0-alpha.30
React latest

Metadata

Metadata

Assignees

No one assigned

    Labels

    duplicateThis issue or pull request already exists.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions