Last active
March 10, 2019 09:15
-
-
Save shinyoshiaki/c0b0bef2fec234041d9173b9cebe0260 to your computer and use it in GitHub Desktop.
path to json tree on react
This file contains hidden or 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
| import React from "react"; | |
| import { storiesOf } from "@storybook/react"; | |
| import Component, { Props } from "."; | |
| const props: Props = { | |
| paths: [ | |
| "src/test/1.ts", | |
| "src/test/2.ts", | |
| "src/components/index.tsx", | |
| "src/components/atoms/index.tsx", | |
| "package.json", | |
| "src/components/atoms/stories.tsx", | |
| "src/components/molecules/stories.tsx" | |
| ] | |
| }; | |
| storiesOf("molecules", module).add("filetree", () => <Component {...props} />); |
This file contains hidden or 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
| import React, { FunctionComponent } from "react"; | |
| import _ from "lodash"; | |
| export interface Props { | |
| paths: string[]; | |
| } | |
| function parsePath(paths: string[]) { | |
| const dirs = paths.map(path => { | |
| const dir: any = {}; | |
| const arr = path.split("/"); | |
| arr.reduce((o, s, i) => { | |
| if (i === arr.length - 1) return (o[arr[i - 1]] = [s]); | |
| else return (o[s] = {}); | |
| }, dir); | |
| return dir; | |
| }); | |
| const filesystem = {}; | |
| dirs.forEach(dir => { | |
| _.mergeWith(filesystem, dir, (a, b) => { | |
| if (_.isArray(a)) { | |
| return b.concat(a); | |
| } | |
| }); | |
| }); | |
| console.log({ filesystem }); | |
| return filesystem; | |
| } | |
| const Traverse: FunctionComponent<{ dirs: any }> = ({ dirs }) => { | |
| const keys = Object.keys(dirs); | |
| return ( | |
| <ul> | |
| {keys.map(key => { | |
| console.log({ key }); | |
| const data: any = dirs[key]; | |
| console.log({ data }); | |
| return ( | |
| <li> | |
| {_.isArray(data) ? ( | |
| data.map((str: any) => <div key={str}>{str}</div>) | |
| ) : ( | |
| <div> | |
| {key} | |
| <Traverse dirs={data} /> | |
| </div> | |
| )} | |
| </li> | |
| ); | |
| })} | |
| </ul> | |
| ); | |
| }; | |
| const FileTree: FunctionComponent<Props> = ({ paths }) => { | |
| return ( | |
| <div> | |
| <Traverse dirs={parsePath(paths)} /> | |
| </div> | |
| ); | |
| }; | |
| export default FileTree; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment