Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recursively analyze and modify descendants of a component in React?

Tags:

reactjs

I am writing a form wrapper, and I want it to dynamically update the descendants to add error messages and add error styling for form elements that have validation errors.

I know I can use React.Children.map to iterate over the children, but I need to recursively iterate over all descendants, searching for <input> and <button> elements.

Any thoughts on how to do this?

Example:

const FormWrapper = (props) => {
  let children = this.props.children;

  if (this.prop.disabled) {
    // Note:  do something here with children to recursively
    // look for form elements, update their props.
  }

  return (
    <form>
      {children}
    </form>
  );
}

Usage:

<FormWrapper errors={this.errors}>
  <div className="row">
    <div className="col">
      <label>Email:</label>
      <input type="text" name="email">
    </div>
  </div>

  <div className="row">
    <div className="col">
      <label>Password</label>
      <input type="password" name="password">
    </div>
  </div>
</FormWrapper>
like image 452
Luke Ehresman Avatar asked Nov 20 '25 20:11

Luke Ehresman


2 Answers

There is no clean, optimal and viable way to recurse down the children graph. You will find hacks (such as manually invoking render on the children) but nothing clean.

like image 107
Sylvain Avatar answered Nov 23 '25 15:11

Sylvain


Thanks to everyone for the ideas, but the actual solution was to use React contexts to push the error messages down to the child components. Works like a charm.

https://reactjs.org/docs/context.html

like image 35
Luke Ehresman Avatar answered Nov 23 '25 13:11

Luke Ehresman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!