-
-
Notifications
You must be signed in to change notification settings - Fork 51
-
Does anyone know how to set the default mode on a tree to expand all the rows?
I do this now using an useEffect()
calling tree.fns.onAddAll(data.map((item) => item.id))
which is called when the page loads, but it's kinda funky and you can see it flipping from the default collapse mode.
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 1 reply
-
1. Best Approaches
Using initialState
const INITIAL_STATE = { expanded: data.map(item => item.id) }; const tree = useTree( data, { state: INITIAL_STATE }, );
Using getState
const tree = useTree( data, { getState: (state) => ({ ...state, expanded: data.map(item => item.id) }) }, );
2. Why This Happens
The "flash" occurs because:
- React renders initial collapsed state
- useEffect runs after mount
- State updates
- Component re-renders
3. Better Solutions
Cleaner useEffect (if needed)
const tree = useTree(data); useEffect(() => { // Use requestAnimationFrame to prevent flash requestAnimationFrame(() => { tree.fns.onAddAll(data.map(item => item.id)); }); }, [data]); // Depend on data
Pre-processing Data
// Helper to expand all nodes const expandAllNodes = (items) => { return items.map(item => ({ ...item, expanded: true, children: item.children ? expandAllNodes(item.children) : [] })); }; // Process data before passing to table const expandedData = expandAllNodes(data); const tree = useTree(expandedData);
4. Best Practices
- Prefer declarative approaches (initialState/getState)
- Avoid side effects when possible
- Consider performance with large datasets
- Test with different data volumes
5. Combined Approach (if needed)
const INITIAL_STATE = { expanded: data.map(item => item.id) }; const tree = useTree( data, { state: INITIAL_STATE, getState: (state) => ({ ...state, expanded: data.map(item => item.id) }) }, );
Key Points:
- Avoid useEffect if possible
- Use initial state when you can
- Consider performance implications
- Test with various data sizes
The initialState or getState approaches are recommended because they:
- Are more declarative
- Avoid side effects
- Prevent visual "flash"
- More performant
Choose based on your specific needs and data structure.
Beta Was this translation helpful? Give feedback.
All reactions
-
wow, thanks @mannuelst for that comprehensive reply!
I tried the suggestions and sadly it didn't work for me. Perhaps because I'm using preact (and not native react)?
There is no expanded
in the tree library as I could find, so I had to replace this with ids
like:
const INITIAL_STATE = { ids: data.map((item) => item.id) };;
But you still get the refresh "flash", also with using the useEffect() with a requestAnimationFrame()
call.
Also I don't have a getState
function. Is that something from redux?
Beta Was this translation helpful? Give feedback.