Autofocus on the first empty TextField Mui
Asked Answered
R

2

0

I'm trying to achieve autofocus functionality when fields are empty .. but in this situation autoFocus always works

<Controller
                      name="sum"
                      control={control}
                      render={({ field: { value, onChange } }) => (
                        <TextField
                          value={money || value}
                          onChange={onChange}
                          error={!!errors?.sum}
                          autoFocus={!value}
                          helperText={errors?.sum && errors.sum?.message}
                          InputProps={{
                            placeholder: 'Например, 100 000 000',
                            endAdornment: (
                              <InputAdornment position="end">
                                <SvgRoubleIcon />
                              </InputAdornment>
                            ),
                            inputComponent: CurrencyInput,
                          }}
               
                        />
                      )}
                    />
Rumilly answered 25/5, 2022 at 12:24 Comment(2)
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.Claymore
when fields are empty then I want to add autoFocusRumilly
I
0

Have you try use it like this

import React from "react";
import ReactDOM from "react-dom";
import { useForm, Controller } from "react-hook-form";
import { TextField } from "@material-ui/core";
import NumberFormat from "react-number-format";

import "./index.css";

function App() {
  const ref = React.createRef(null);
  const defaultValues = {
    firstName: '',
  };
  const {
    handleSubmit,
    control,
    formState: { errors }
  } = useForm({defaultValues});

  const onSubmit = (data) => {
    console.log(data);
  };
  React.useEffect(() => {
    console.log(ref)
  })

  return (
    <div className="App">
      <form onSubmit={handleSubmit(onSubmit)}>
        <Controller
          name="firstName"
          control={control}
          rules={{ required: true }}
          render={({ field: { value, ref, ...field } }) => {
            console.log(field,value)
            return <TextField
              {...field}
              inputRef={ref}
              value={value}
              id="firstName"
              autoComplete="fname"
              variant="outlined"
              fullWidth
              autoFocus={!value}
              error={!!errors.firstName}
              label="First Name"
          />
          }}
        />
        <input type="submit" />
      </form>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Live example is Real example

Ingather answered 25/5, 2022 at 12:31 Comment(2)
value - from where you getRumilly
I have update my answer , if you change defaultValues firstName , you can see that focus will not active after the mount @RumillyIngather
I
0

One issue with using the autoFocus attribute is that's it's a hassle to develop with due to the different behavior when using npm run dev. I was never able to get that approach to work properly. Note also that it's important to not let value be undefined in some cases.

Using a ref works well:

import { useEffect, useRef, useState } from 'react';

export default function Index() {
  const [fieldOne, setFieldOne] = useState(fieldOneInitialValue)
  const [fieldTwo, setFieldTwo] = useState('')

  const fieldOneRef = useRef(null);
  const fieldTwoRef = useRef(null);

  useEffect(() => {
    if (fieldOne.length > 0) {
      fieldTwoRef.current.focus();
    } else {
      fieldOneRef.current.focus();
    }
  }, []);

  return (
    <>
      <TextField
        value={fieldOne}
        inputRef={fieldOneRef}
        label="Field 1"
        InputLabelProps={{ shrink: true }}
        onChange={(e) => setFieldOne(e.target.value)} />
      <TextField
        value={fieldTwo}
        inputRef={fieldTwoRef}
        label="Field 2"
        onChange={(e) => setFieldTwo(e.target.value)} />
    </>
  )  
}
Illampu answered 18/10 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.