From 40645d7b43d5f4d99cfa749a83a04dbbb2edc801 Mon Sep 17 00:00:00 2001 From: Jon Thompson Date: Sun, 27 May 2018 14:08:49 +0100 Subject: [PATCH] feat(withTouchedErrors): Add HOC to help simplify form libs integration --- src/helpers/withTouchedErrors.react.js | 39 ++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/helpers/withTouchedErrors.react.js diff --git a/src/helpers/withTouchedErrors.react.js b/src/helpers/withTouchedErrors.react.js new file mode 100644 index 00000000..6f6c1a85 --- /dev/null +++ b/src/helpers/withTouchedErrors.react.js @@ -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 } { + 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 = []) { + return function withComponent( + Component: React.ComponentType + ): React.ComponentType { + return function WithTouchedErrors(props: A) { + const errors = touchedErrors(props.touched, props.errors, fields); + return ; + }; + }; +} + +export default withTouchedErrors;