catho/quantum

Form validate for nested child inputs

Agezao opened this issue ยท 4 comments

Hi.
Right now the <Form> validation through Validations is only possible if the given input is a direct child of the <Form> element, ignoring nested child inputs;

Example:

Works fine:

image

Breaks:

image

Are we doing something wrong? Is this an intended behavior or is this really a bug?

Thanks!

Apparently, we can recursively check the child-inputs here instead of the shallow check given by React.Children.map:
https://github.com/catho/quantum/blob/master/components/Form/Form.jsx#L100

Can this deep check possibly break something else? ๐Ÿค”
I'm not a quantum expert hahah

edit: is this a similar issue? https://stackoverflow.com/questions/32916786/react-children-map-recursively

Thanks for your help @Agezao , we put a task in the backlog to solve this issue.

This fix is not quite simple, the "_createClones" method replaces the child "Input" component by a clone with modified properties. This can only be done with direct children. The "Form" component cannot replace the "Input" components that are inside other components.

  _createClones = children => {
    const { values, errors } = this.state;

    return React.Children.map(children, child => {
      if (!Form._isValidElement(child)) {
        return child;
      }

      const { name, error, onChange = () => {} } = child.props;
      return React.cloneElement(child, {
        value: values[name],
        error: errors[name] || error,
        onChange: e => {
          this._handleChange(e);
          onChange(e);
        },
      });
    });
  };
  render() {
    // Removing invalid form props, to avoid warnings
    const _props = { ...this.props };
    const { children } = _props;
    delete _props.onValidSubmit;

    return (
      <form {..._props} onSubmit={this.handleSubmit}>
        {this._createClones(children)}
      </form>
    );
  }
}

๐ŸŽ‰ This issue has been resolved in version 6.4.10 ๐ŸŽ‰

The release is available on:

Your semantic-release bot ๐Ÿ“ฆ๐Ÿš€