Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React -- how to break out of ' React.Children.forEach ' loop?

Tags:

reactjs

If I'm looping through a react component's children like so:

React.Children.forEach(this.props.children, (child) => {

       //checking child's props and such...
      if (child.props[someprop] == some condition) {
         break out of loop here
      }
});

But how does one break out of this loop? I want to check certain props on the children and break out on a condition. Is there a break or exit for or something for this? Or is there another way to loop through React's children?

like image 936
Coco Avatar asked Dec 04 '25 23:12

Coco


1 Answers

You cant break out of the forEach but you could use the toArray method like so:

const children = React.Children.toArray(this.props.children);
for ( let child of children ) {
    if (child.props[someprop] == some condition) {
        break;
    }
}
like image 136
DiverseAndRemote.com Avatar answered Dec 06 '25 12:12

DiverseAndRemote.com