Tuesday, 27 August 2019

Forming the components based on the array of objects : ReactJS

For a setting page for an application, I have implemented a slider that has enabled(green) or disabled(red) state. And parent's settings are calculated based on the values of its children.

//Getting the switches configuration inside componnetDidMount something like this

var obj = [
  {
    parent_header_name: "parent1",
    children_info: [
      {
        child_switch_name: "child1",
        isEnabled: true
      },
      {
        child_switch_name: "child2",
        isEnabled: false
      }
    ]
  },
  {
    parent_header_name: "parent2",
    children_info: [
      {
        child_switch_name: "child3",
        isEnabled: true
      }
    ]
  },
  {
    parent_header_name: "parent3",
    children_info: [
      {
        child_switch_name: "child4",
        isEnabled: false
      }
    ]
  }
];

Now based on this value, I need to form a grouping of parent and children something like this:

Label(the value should be parent_header_name) : Parent Switch Component
Label for children(children_switch_name) : Child Switch Component

Also on change of individual children switches toggling I need to get the info of that switch something like this:

For Example, Changing parent1's child1's to disabled

[
  {
    parent_header_name: "parent1",
    children_info: [
      {
        child_switch_name: "child1",
        isEnabled: false
      }
    ]
  }
];

In case parent1 turned to enabled I need to get all its chidren value

[
  {
    parent_header_name: "parent1",
    children_info: [
      {
        child_switch_name: "child1",
        isEnabled: true
      },
      {
        child_switch_name: "child2",
        isEnabled: true
      }
    ]
  }
]


And when parents switch is toggled(when the parent is enabled, children will be enabled and when disabled children will be disabled;), I need to get the entire info of that parent

Also, I need to avoid toggling to "partial" state, the parent should only be enabled or disabled. "Partial" is only representational

For this, I am using react-multi-toggle for this toggle switch.

I have tried something like this: https://codesandbox.io/s/parent-child-switches-gxfx6



from Forming the components based on the array of objects : ReactJS

No comments:

Post a Comment