Home > Blockchain >  Binding data to treeview nodes from array issue in react
Binding data to treeview nodes from array issue in react

Time:01-05

I have follow below example to create tree view with check boxes. Its working fine.

https://github.com/jakezatecky/react-checkbox-tree

Now I am trying to add data from my post method. I have fill data to array. But I tried to add it to loop for get data.

const persons = []; 
for (let i = 0; i < data.length; i  ) {
  persons = [{ value: data[i].id, label: data[i].name }]; 
}  
this.setState({ persons });

Checkbox code

  render() {
        return (
            <CheckboxTree
                nodes={this.state.persons}
                iconsClass="fa5"
                checked={this.state.checked}
                expanded={this.state.expanded} 
                onExpand={expanded => this.setState({ expanded })}
            />
        );
    }

I am getting only last record in this treeview. but loop is working correctly Please give some suggestions to solve this. thank you

CodePudding user response:

You are getting the last object only because you are re-initialing the person array each time.

Instead you have to push that object to the array.

Try like this:

const persons = [];
for (let i = 0; i < data.length; i  ) {
  persons.push({ value: data[i].id, label: data[i].name }) 
}
this.setState({ persons });
  • Related