- 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' />
