1

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

1 Answer 1

2

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 });
Sign up to request clarification or add additional context in comments.

7 Comments

If your issue is resolved then you can give a up-vote for my motivation :).....
@Bidhudatta Done. Sorry for late
I have a small question regarding this. If I have children inside this one. then can we use it inside this one without loop it @Bibhudatta Sahoo
Yes if you have children record then you can add the object children at place of Value label.
you meant like this persons.push({ value: data[i].id, label: data[i].name, children: [ { value: data[i].id, label: data[i].name}] })
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.