Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: controlled text input #3145

Merged
merged 7 commits into from
Apr 26, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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