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

[bug] An input initializes without visible value when autofocus is enabled #3

Open
mirus-ua opened this issue Nov 10, 2023 · 1 comment

Comments

@mirus-ua
Copy link

Hello. When I tried to use autoFocus, it behaved oddly, both in the case of the mui component and regular HTML's input. When the input is rendered, it looks blank (the first screenshot) even if it has a value, like in the code snippet, and the value appears only after the user's action, like click or key press (the second screenshot after arrow up press).

As far as I understood, this behavior is related to the philosophy of the library, but is it possible to fix it, or do I need to find a workaround?

The base component snippet

import TextField from '@mui/material/TextField';

const NumberField = (props: NumberFieldProps) => {
  const formattedInput = useFormattedInput(
    intlNumberFormatter({
      locales: props.locale,
      value: props.value,
      onChange: props.onChange,
      liveUpdate: true,
      ...props,
    }),
  );

  const { ref, ...rest } = formattedInput.props;
  return <TextField {...restProps} InputProps={{ ...rest, inputRef: ref }} />;
}

The usage of the base component

const Usage = () => {
  const [value, setValue] = useState<number | null>(12345.67);
  return (
      <NumberField
        autoFocus
        label="A number field"
        value={value}
        onChange={setValue}
      />
  )
}

empty when autoFocused
Знімок екрана 2023-11-10 о 09 11 22

@mirus-ua
Copy link
Author

As a workaround I use programatic approach instead of native DOM attribute.

const NumberField = ({
  value,
  onChange,
  autoFocus,
  ...restProps
}: NumberFieldProps) => {
  const formattedInput = useFormattedInput(
    intlNumberFormatter({
      locales: props.locale,
      value: props.value,
      onChange: props.onChange,
      liveUpdate: true,
      ...props,
    }),
  );

  const { ref, ...rest } = formattedInput.props;

  useEffect(() => {
    if (formattedInput.props.ref.current && autoFocus === true) {
      formattedInput.props.ref.current.focus();
    }
  }, [formattedInput.props.ref.current == null, autoFocus]);

  return <TextField {...restProps} InputProps={{ ...rest, inputRef: ref }} />;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant