Luke Ehresman
Luke Ehresman

Reputation: 5257

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

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>

Upvotes: 3

Views: 712

Answers (2)

Luke Ehresman
Luke Ehresman

Reputation: 5257

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

Upvotes: 1

Sylvain
Sylvain

Reputation: 19249

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.

Upvotes: 1

Related Questions