A
A
Amir2017-08-21 15:18:25
recursion
Amir, 2017-08-21 15:18:25

How to create a recursive component correctly?

I have view data:

{
  name: "Name",
  required: true,
  type: "object",
  properties: [
    {
      name: "Name2",
      required: false,
      type: "object",
      properties: [
      {
        name: "Name3",
        required: false,
        type: "text"
      },
      {
        name: "Name4",
        required: false,
        type: "text"
      }
      ]
    },
    {
      name: "Name5",
      required: false,
      type: "text"
    }
  ]
}

Accordingly, nesting can be any. I'm trying to create a component that would recursively render this data:
import React, { Component } from 'react';

export default class PropertiesParser extends Component {
    render() {
        let propers = this.props.properties;
        if (propers) {
            switch (propers.type) {
                case "text":
                    return (
                        <div className="row">
                            <div className="col-md-2">
                                {propers.name}
                            </div>
                            <div className="col-md-10">
                                <input
                                    type="text"
                                    name={propers.name}
                                    required={propers.required}
                                    value="" />
                            </div>
                        </div>
                    );
                    break;

                case "object":
                    return (<div>{propers.properties.map(property => 
                        <PropertiesParser key={propers.Name + Math.random()} properties={property} />
                    )}</div>);
                    break;
            }

        }
    
        return (
            <div>
            </div>
        );
    }
}

But when I try to check the operation of this code, it does not work, and an error is written in the console:
Uncaught RangeError: Maximum call stack size exceeded

When I inserted console.log(propers) at the beginning of the render, the console was filled with repeating objects, i.e. if we take the above object as an example, then in the console I will see a bunch of repeating:

{name: "Name", required: true, properties: Array(2), type: "object"}
{name: "Name2", required: true, type: "object"}
...

Etc. What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question