Skip to content

Commit

Permalink
fix: controlled text input (#3145)
Browse files Browse the repository at this point in the history
Co-authored-by: Luke Walczak <[email protected]>
  • Loading branch information
seahorsepip and lukewalczak authored Apr 26, 2022
1 parent 60db400 commit fcd402e
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions src/components/TextInput/TextInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,8 @@ const TextInput = React.forwardRef<TextInputHandles, TextInputProps>(
}: TextInputProps,
ref
) => {
const validInputValue =
rest.value !== undefined ? rest.value : rest.defaultValue;
const isControlled = rest.value !== undefined;
const validInputValue = isControlled ? rest.value : rest.defaultValue;

const { current: labeled } = React.useRef<Animated.Value>(
new Animated.Value(validInputValue ? 0 : 1)
Expand All @@ -220,9 +220,12 @@ const TextInput = React.forwardRef<TextInputHandles, TextInputProps>(
const [placeholder, setPlaceholder] = React.useState<string | undefined>(
''
);
const [value, setValue] = React.useState<string | undefined>(
validInputValue
);
const [uncontrolledValue, setUncontrolledValue] = React.useState<
string | undefined
>(validInputValue);
// Use value from props instead of local state when input is controlled
const value = isControlled ? rest.value : uncontrolledValue;

const [labelLayout, setLabelLayout] = React.useState<{
measured: boolean;
width: number;
Expand Down Expand Up @@ -262,10 +265,6 @@ const TextInput = React.forwardRef<TextInputHandles, TextInputProps>(
forceFocus: () => root.current?.focus(),
}));

React.useLayoutEffect(() => {
if (typeof rest.value !== 'undefined') setValue(rest.value);
}, [rest.value]);

React.useEffect(() => {
// When the input has an error, we wiggle the label and apply error styles
if (errorProp) {
Expand Down Expand Up @@ -376,7 +375,10 @@ const TextInput = React.forwardRef<TextInputHandles, TextInputProps>(
return;
}

setValue(value);
if (!isControlled) {
// Keep track of value in local state when input is not controlled
setUncontrolledValue(value);
}
rest.onChangeText?.(value);
};

Expand Down

0 comments on commit fcd402e

Please sign in to comment.