add collapse/expand all feature for react-json-tree

This commit is contained in:
lucataglia 2023-05-18 15:33:28 +02:00
parent 58a8135b08
commit 5961ae4cba
3 changed files with 14 additions and 1 deletions

View File

@ -1,4 +1,4 @@
import React, { useCallback, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import JSONArrow from './JSONArrow'; import JSONArrow from './JSONArrow';
import getCollectionEntries from './getCollectionEntries'; import getCollectionEntries from './getCollectionEntries';
import JSONNode from './JSONNode'; import JSONNode from './JSONNode';
@ -110,6 +110,7 @@ export default function JSONNestedNode(props: Props) {
nodeType, nodeType,
nodeTypeIndicator, nodeTypeIndicator,
shouldExpandNodeInitially, shouldExpandNodeInitially,
shouldExpandNode,
styling, styling,
} = props; } = props;
@ -117,7 +118,16 @@ export default function JSONNestedNode(props: Props) {
// calculate individual node expansion if necessary // calculate individual node expansion if necessary
isCircular ? false : shouldExpandNodeInitially(keyPath, data, level) isCircular ? false : shouldExpandNodeInitially(keyPath, data, level)
); );
useEffect(() => {
if(shouldExpandNode === undefined){
return
}
setExpanded(shouldExpandNode);
}, [shouldExpandNode])
const handleClick = useCallback(() => { const handleClick = useCallback(() => {
if (expandable) setExpanded(!expanded); if (expandable) setExpanded(!expanded);
}, [expandable, expanded]); }, [expandable, expanded]);

View File

@ -41,6 +41,7 @@ export function JSONTree({
labelRenderer = defaultLabelRenderer, labelRenderer = defaultLabelRenderer,
valueRenderer = identity, valueRenderer = identity,
shouldExpandNodeInitially = expandRootNode, shouldExpandNodeInitially = expandRootNode,
shouldExpandNode,
hideRoot = false, hideRoot = false,
getItemString = defaultItemString, getItemString = defaultItemString,
postprocessValue = identity, postprocessValue = identity,
@ -64,6 +65,7 @@ export function JSONTree({
labelRenderer={labelRenderer} labelRenderer={labelRenderer}
valueRenderer={valueRenderer} valueRenderer={valueRenderer}
shouldExpandNodeInitially={shouldExpandNodeInitially} shouldExpandNodeInitially={shouldExpandNodeInitially}
shouldExpandNode={shouldExpandNode}
hideRoot={hideRoot} hideRoot={hideRoot}
getItemString={getItemString} getItemString={getItemString}
postprocessValue={postprocessValue} postprocessValue={postprocessValue}

View File

@ -47,6 +47,7 @@ export interface CommonExternalProps {
labelRenderer: LabelRenderer; labelRenderer: LabelRenderer;
valueRenderer: ValueRenderer; valueRenderer: ValueRenderer;
shouldExpandNodeInitially: ShouldExpandNodeInitially; shouldExpandNodeInitially: ShouldExpandNodeInitially;
shouldExpandNode: boolean | undefined;
hideRoot: boolean; hideRoot: boolean;
getItemString: GetItemString; getItemString: GetItemString;
postprocessValue: PostprocessValue; postprocessValue: PostprocessValue;