0
votes

I'm working with two functional react components where I'm passing an id (the state) of a clicked item down to a child component via a prop.

Problem

The id does render in the child component, but when the state is updated in the parent the child component creates a new render instead of updating the previous render. So eg. the child component displays the id 1 and when another item is clicked the child component displays both 1 and new id

Parent class:

import ReactDOM from "react-dom";
import React from "react";
import TreeView from "@material-ui/lab/TreeView";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import TreeItem from "@material-ui/lab/TreeItem";
import Test from "./test";
const { useState, useCallback } = React;

export default function MyTreeItem(props) {
  const [childNodes, setChildNodes] = useState(null);
  const [expanded, setExpanded] = React.useState([]);
  const [activeItemId, setActiveItemId] = useState();

  function fetchChildNodes(id) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({
          children: [
            {
              id: "2",
              name: "Calendar"
            },
            {
              id: "3",
              name: "Settings"
            },
            {
              id: "4",
              name: "Music"
            }
          ]
        });
      }, 1000);
    });
  }

  const handleChange = (event, nodes) => {
    const expandingNodes = nodes.filter(x => !expanded.includes(x));
    setExpanded(nodes);
    if (expandingNodes[0]) {
      const childId = expandingNodes[0];
      fetchChildNodes(childId).then(result =>
        setChildNodes(
          result.children.map(node => <MyTreeItem key={node.id} {...node} />)
        )
      );
    }
  };

  const renderLabel = item => (
    <span
      onClick={event => {
        console.log(item.id);
        setActiveItemId(item.id);
        // if you want after click do expand/collapse comment this two line
        event.stopPropagation();
        event.preventDefault();
      }}
    >
      {item.name}
    </span>
  );

  return (
    <div>
      <TreeView
        defaultCollapseIcon={<ExpandMoreIcon />}
        defaultExpandIcon={<ChevronRightIcon />}
        expanded={expanded}
        onNodeToggle={handleChange}
      >
        {/*The node below should act as the root node for now */}
        <TreeItem nodeId={props.id} label={renderLabel(props)}>
          {childNodes || [<div key="stub" />]}
        </TreeItem>
      </TreeView>
      <Test test={activeItemId} />
    </div>
  );
}
const rootElement = document.getElementById("root");
ReactDOM.render(<MyTreeItem id="1" name="Applications" />, rootElement);


Child class:

import React, { useState, useEffect } from "react";

export default function Test({ test }) {
  return <h1>{test}</h1>;
}

To reproduce the problem: https://codesandbox.io/s/material-demo-5kfbl

1
I am not seeing 1 displayed anywhere. It seems to work as expected. - jmargolisvt
If you click on the Applications label, 1 is displayed. If you expand the Applicationsnode and click on Calendar 2 is displayed. - John

1 Answers

0
votes

Problem comes from [unexpected] recurrency - setChildNodes renders 'tree root' components <MyTreeItem /> as childs, each of them with own states, handlers etc.

You can fix this by render <TreeItem /> as childs:

    setChildNodes(
      result.children.map(node => <TreeItem nodeId={node.id} label={renderLabel(node)} /> )
    )

Working example: https://codesandbox.io/s/material-demo-k8mq1