Skip to content

Commit

Permalink
Update FieldTextInput: use defaultValue if uncontrolled
Browse files Browse the repository at this point in the history
  • Loading branch information
Gnito committed Jul 17, 2019
1 parent c817436 commit c2e7079
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions src/components/FieldTextInput/FieldTextInput.js
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -22,6 +22,8 @@ class FieldTextInputComponent extends Component {
input,
meta,
onUnmount,
isUncontrolled,
inputRef,
...rest
} = this.props;
/* eslint-enable no-unused-vars */
Expand All @@ -41,16 +43,32 @@ 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, {
[css.inputSuccess]: valid,
[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 (
Expand All @@ -71,6 +89,8 @@ FieldTextInputComponent.defaultProps = {
customErrorText: null,
id: null,
label: null,
isUncontrolled: false,
inputRef: null,
};

FieldTextInputComponent.propTypes = {
Expand All @@ -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,
Expand Down

0 comments on commit c2e7079

Please sign in to comment.