Last active
February 23, 2019 11:22
-
-
Save mrroot5/a1b51b4a6967bb5f57e1d21867bb9e71 to your computer and use it in GitHub Desktop.
React treeview
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.tree-element { | |
margin: 0; | |
position: relative; | |
} | |
div.tree-element:before { | |
content: ''; | |
position: absolute; | |
top: 24px; | |
left: 1px; | |
height: calc(100% - 48px); | |
border-left: 1px solid gray; | |
} | |
.toggler { | |
position: absolute; | |
top: 10px; | |
left: 0px; | |
width: 0; | |
height: 0; | |
border-top: 4px solid transparent; | |
border-bottom: 4px solid transparent; | |
border-left: 5px solid gray; | |
cursor: pointer; | |
} | |
.toggler.closed { | |
transform: rotate(90deg); | |
} | |
.collapsed { | |
display: none; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function TreeView({ | |
data, | |
toggled = true, | |
name = null, | |
isLast = true, | |
isChildElement = false, | |
isParentToggled = true | |
}) { | |
const [isToggled, setIsToggled] = React.useState(toggled); | |
return ( | |
<div | |
style={{ marginLeft: isChildElement ? 16 : 4 + "px" }} | |
className={isParentToggled ? "tree-element" : "tree-element collapsed"} | |
> | |
<span | |
className={isToggled ? "toggler" : "toggler closed"} | |
onClick={() => setIsToggled(!isToggled)} | |
/> | |
{name ? <strong> {name}: </strong> : <span> </span>} | |
{Array.isArray(data) ? "[" : "{"} | |
{!isToggled && "..."} | |
{Object.keys(data).map( | |
(v, i, a) => | |
typeof data[v] == "object" ? ( | |
<TreeView | |
data={data[v]} | |
isLast={i === a.length - 1} | |
name={Array.isArray(data) ? null : v} | |
isChildElement | |
isParentToggled={isParentToggled && isToggled} | |
/> | |
) : ( | |
<p | |
style={{ marginLeft: 16 + "px" }} | |
className={isToggled ? "tree-element" : "tree-element collapsed"} | |
> | |
{Array.isArray(data) ? "" : <strong>{v}: </strong>} | |
{data[v]} | |
{i === a.length - 1 ? "" : ","} | |
</p> | |
) | |
)} | |
{Array.isArray(data) ? "]" : "}"} | |
{!isLast ? "," : ""} | |
</div> | |
); | |
} | |
let data = { | |
lorem: { | |
ipsum: "dolor sit", | |
amet: { | |
consectetur: "adipiscing", | |
elit: [ | |
"duis", | |
"vitae", | |
{ | |
semper: "orci" | |
}, | |
{ | |
est: "sed ornare" | |
}, | |
"etiam", | |
["laoreet", "tincidunt"], | |
["vestibulum", "ante"] | |
] | |
}, | |
ipsum: "primis" | |
} | |
}; | |
ReactDOM.render(<TreeView data={data} name='data'/>, document.getElementById("root")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment