diff --git a/snippets/TreeView.md b/snippets/TreeView.md new file mode 100644 index 000000000..de2e1bf52 --- /dev/null +++ b/snippets/TreeView.md @@ -0,0 +1,126 @@ +### TreeView + +Renders a tree view of a JSON object or array with collapsible content. + +Use `defaultProps` to set the default values of certain props. +Use the value of the `toggled` prop to determine the initial state of the content (collapsed/expanded). +Set the `state` of the component to the value of the `toggled` prop and bind the `toggle` method to the component's context. +Create a method, `toggle`, which uses `Component.prototype.setState` to change the component's `state` from collapsed to expanded and vice versa. +In the `render()` method, use a `
` element with the appropriate style. + +```css +.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; +} +``` + +```jsx +class TreeView extends React.Component { + constructor(props) { + super(props); + this.state = { + toggled: props.toggled + } + this.toggle = this.toggle.bind(this); + } + + toggle() { + this.setState(state => ({ toggled: !state.toggled })); + } + + render() { + return ( +
+ {Array.isArray(this.props.data) ? '' : {v}: } + {this.props.data[v]}{i === a.length - 1 ? '' : ','} +
+ ) + )} + {Array.isArray(this.props.data) ? ']' : '}'} + {!this.props.isLast ? ',' : ''} +