From fb2c11cae2df78fad8e3cb5e577d134e224fc0af Mon Sep 17 00:00:00 2001 From: Vesa Luusua Date: Tue, 16 Jul 2019 14:19:32 +0300 Subject: [PATCH] Update FieldTextInput: use defaultValue if uncontrolled --- .../FieldTextInput/FieldTextInput.js | 32 +++++++++++++++++-- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/src/components/FieldTextInput/FieldTextInput.js b/src/components/FieldTextInput/FieldTextInput.js index 878738ee..368f5615 100644 --- a/src/components/FieldTextInput/FieldTextInput.js +++ b/src/components/FieldTextInput/FieldTextInput.js @@ -1,5 +1,5 @@ import React, { Component } from 'react'; -import { func, object, shape, string } from 'prop-types'; +import { bool, func, object, shape, string } from 'prop-types'; import { Field } from 'react-final-form'; import classNames from 'classnames'; import { ValidationError, ExpandingTextarea } from '../../components'; @@ -22,6 +22,8 @@ class FieldTextInputComponent extends Component { input, meta, onUnmount, + isUncontrolled, + inputRef, ...rest } = this.props; /* eslint-enable no-unused-vars */ @@ -41,6 +43,11 @@ class FieldTextInputComponent extends Component { const fieldMeta = { touched: hasError, error: errorText }; + // Uncontrolled input uses defaultValue instead of value. + const { value: defaultValue, ...inputWithoutValue } = input; + // Use inputRef if it is passed as prop. + const refMaybe = inputRef ? { ref: inputRef } : {}; + const inputClasses = inputRootClass || classNames(css.input, { @@ -48,9 +55,20 @@ class FieldTextInputComponent extends Component { [css.inputError]: hasError, [css.textarea]: isTextarea, }); + const maxLength = CONTENT_MAX_LENGTH; const inputProps = isTextarea - ? { className: inputClasses, id, rows: 1, maxLength: CONTENT_MAX_LENGTH, ...input, ...rest } - : { className: inputClasses, id, type, ...input, ...rest }; + ? { className: inputClasses, id, rows: 1, maxLength, ...refMaybe, ...input, ...rest } + : isUncontrolled + ? { + className: inputClasses, + id, + type, + defaultValue, + ...refMaybe, + ...inputWithoutValue, + ...rest, + } + : { className: inputClasses, id, type, ...refMaybe, ...input, ...rest }; const classes = classNames(rootClassName || css.root, className); return ( @@ -71,6 +89,8 @@ FieldTextInputComponent.defaultProps = { customErrorText: null, id: null, label: null, + isUncontrolled: false, + inputRef: null, }; FieldTextInputComponent.propTypes = { @@ -92,6 +112,12 @@ FieldTextInputComponent.propTypes = { // Either 'textarea' or something that is passed to the input element type: string.isRequired, + // Uncontrolled input uses defaultValue prop, but doesn't pass value from form to the field. + // https://reactjs.org/docs/uncontrolled-components.html#default-values + isUncontrolled: bool, + // a ref object passed for input element. + inputRef: object, + // Generated by final-form's Field component input: shape({ onChange: func.isRequired,