Search code examples
reactjsantd

Antd - How to expand all tree items by default in Table with async data?


  • The context: I want to create a tree-like Table using the component <Table /> of antd, the data source is loaded asynchronously from the server. And when the data is loaded, I want all the nodes to be expanded.

  • Current situation: code sandbox. There are 2 weird points remain:

  1. Look at the images, when in the red rectangle the value is null, the nodes are expanded by default (which is what I want), but when the value in the rectangle is a clone dummy <Table />, the nodes are not expanded, why? Whether is it null nor Table, both would not be used anyway? enter image description hereenter image description
here

  2. When I click on the collapse button [-] near Phòng ban kinh doanh which is a level 2 node, why does it collapse all the tree? What is wrong with collapsing here? enter image description here

Updated: I have resolved the 2 concern here. Now, how it make the nodes expanded by default?


Solution

    1. Why does the tree expands all by default when rendering the Table conditionally?

    In React, default[YourPropValue] (for example defaultValue, defaultChecked,...) is a term frequently used to describe a prop value that only works when the component first mounts, this value is not used in subsequent renders. The default[YourPropValue] is useful when you want an uncontrolled component where the value is handled by the DOM element, not inside React code, and you want to initialize the value for the first time before React creates an element.

    When you render conditionally based on the current data:

    data ?
      <Table {...props} defaultExpandAllRows />
      :
      null
    

    First there is no data, you return nothing. After the data is fetched, you start rendering the Table. This is the first time React sees you return the Table so it mounts with the defaultExpandAllRows set to true which works as expected.

    The code below behaves differently because when you return the Table for the first time, you doesn't set defaultExpandAllRows (even if you set it, it doesn't matter because there is no data to expand). When the data is fetched, you also return the Table with the populated data. React reuses the last Table component and render for the second time, so the defaultExpandAllRows prop doesn't work anymore:

    data ?
      <Table {...props} dataSource={data} />
      :
      <Table {...props} dataSource={[]} defaultExpandAllRows />
    

    A simple solution to fix it is to tell React that the empty Table and the Table with the populated data is different so it can unmount and remount the component and make the default value applied correctly:

    data ?
      <Table {...props} dataSource={data} defaultExpandAllRows />
      :
      <Table {...props} dataSource={[]} key='dummyTable' />
    

    Codesandbox Demo