Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
First input autofocus for OTP input fields in React

I made OTP input in React You can see this image. One line is one input and I have 6 inputs. The inputs work that is not a problem. I need when the component opens, the first input must be autofocus. When I use <input autofocus/> the last input is autofocus, I need the first input.

My parent component

  const [code, setcode] = useState(new Array(6).fill(""));

OTP component

 <div className="digit-inputs">
        {props.code.map((data, index) => {
          return (
            <input
              disabled={props.second <= 0 ? true : false}
              type="text"
              className="otp-field"
              name="otp"
              maxLength={1}
              key={index}
              style={data ? { borderBottom: "3px solid #7dbf2a" } : { borderBottom: "3px solid grey" }}
              value={data}
              onChange={(e) => handleChange(e.target, index)}
              onFocus={(e) => e.target.select}
            />
          );
        })}
      </div>

My function

  const handleChange = (element, index) => {
    if (isNaN(element.value)) return false;

    props.setcode([...props.code.map((d, indx) => (indx === index ? element.value : d))]);

    //Focus next input

    if (element.nextSibling) {
      element.nextSibling.focus();
    }
  };

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you just wanted the focus when the component mounts, you can use the index of the array. just add autoFocus={index === 0}.

         <input
          type="text"
          className="otp-field"
          name="otp"
          maxLength={1}
          key={index}
          style={
            data
              ? { borderBottom: "3px solid #7dbf2a" }
              : { borderBottom: "3px solid grey" }
          }
          //value={data}
          onFocus={(e) => e.target.select}
          autoFocus={index === 0} // add this line
          //onChange
        />
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda