bietkul / react-reactive-form

Angular like reactive forms in React.
MIT License
309 stars 32 forks source link

Determine if render component has any error #9

Closed AdamBrodzinski closed 6 years ago

AdamBrodzinski commented 6 years ago

First thanks so much for making this library! I haven't used Angular before but i've been really tired of the React forms with so many deps and needless boilerplate.

Anyhow, i've been struggling to find a way to determine if the "render component" has a way to determine if there is any error? My use case is to change the input border to red if any error exists, regardless of it's type.

My workaround is to use an OR clause to check all of them such as:

const TextInput = ({hasError, touched}) => {
  const hasAnyError = touched && (hasError("required") || hasError("email"));
  ...
}

Is there a way to do this in the API? I tried calling hasError with no arguments and that didn't seem to work.

Also since I have your ear, another thing I can't figure out how to do is make all of the inputs "touched" if a user submits the form. Ideally, when they hit submit on a form with errors it would show them at that time. Currently in the "form component" I have a check to see if it's valid and it currently does nothing if it's invalid or submits if it is valid.

Thanks again 🍻

bietkul commented 6 years ago

It's simple to determine that a control has any error or not, you can use the invalid & valid property to check it.

const TextInput = ({hasError, touched, invalid}) => {
   const hasAnyError = touched && invalid;
  ...
}

Every control has a property called submitted which marked as true when you call the onSubmit function, so you can check the submitted property to determine that you're form has been submitted or not. Checkout the Update on Submit Example.

Whenever you want to mark the controls as touched, just call the markAsTouched function on the parent control.

AdamBrodzinski commented 6 years ago

Awesome, thanks for the help!