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>
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With