Search code examples
jsonreactjsreact-nativetraversal

Traverse through JSON and create React components


How can I traverse through my data structure and create React components?

{
  component: "View",
  attributes: {
    id: 'main'
  },
  child: [
    {
      component: "Text",
      content: "Hello World!"
    },
    {
      component: "Link",
      attributes: {
        href: "#"
      },
      child: [
        {
          component: "Text",
          content: "Click me!"
        }
      ]
    }
  ] 
}

Would output:

<View>
  <Text>Hello World!</Text>
  <Link>Click me!</Link>
</View>

How can I dynamically achieve this where it works regardless of the number of nested components?

I am able to make the top level component, but traversing through the child elements is where I hit a brick wall.


Solution

  • You can create a function that calls itself.

    Sample

    parseComponents = (data, key) => {
      if (key === undefined || key === null) key = 0;
      let Component = null;
      switch(data.component) {
        case 'View': 
          Component = View;
          break;
        case 'Text':
          Component = Text;
          break;
        case 'Link':
          Component = Link;
          break;
        default:
          break;
      }
      if (Component === null) return Component;
    
      return (
        <Component key={`${data.component}-${index}`} {...data.attributes}>
          {data.child.map((c, index) => this.parseComponents(c, index))}
        </Component>
      )
    }