This repository was archived by the owner on Mar 1, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 552
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(withTouchedErrors): Add HOC to help simplify form libs integration
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
// @flow | ||
|
||
import * as React from "react"; | ||
|
||
/** | ||
* Returns an object of fields with values set based on the touched and error values | ||
* If a value is both touched and has a non-empty error string it is returned as the fields value | ||
*/ | ||
function touchedErrors( | ||
touched: { [string]: boolean } = {}, | ||
errors: { [string]: string } = {}, | ||
fields: Array<string> = [] | ||
): { [string]: string } { | ||
return fields.reduce( | ||
(acc, cur) => | ||
Object.assign(acc, { | ||
[cur]: touched && touched[cur] && errors ? errors[cur] : "", | ||
}), | ||
{} | ||
); | ||
} | ||
|
||
/** | ||
* A HOC that modifies the errors propso that it only returns errors if the the field | ||
* has also been touched | ||
* First takes an array of the field names, followed by the component | ||
*/ | ||
function withTouchedErrors(fields: Array<string> = []) { | ||
return function withComponent<A: { +touched?: *, +errors?: * }>( | ||
Component: React.ComponentType<A> | ||
): React.ComponentType<A> { | ||
return function WithTouchedErrors(props: A) { | ||
const errors = touchedErrors(props.touched, props.errors, fields); | ||
return <Component {...props} errors={errors} />; | ||
}; | ||
}; | ||
} | ||
|
||
export default withTouchedErrors; |