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

257
Visualizações
How to focus something on next render with React Hooks

I'm playing with hooks, and I'm trying to do the following:

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

const EditableField = () => {
  const [isEditing, setEditing] = useState(false);
  const inputRef = useRef();
  const toggleEditing = () => {
    setEditing(!isEditing);
    if (isEditing) {
      inputRef.current.focus();
    }
  };
  return (
    <>
      {isExpanded && <input ref={inputRef} />}
      <button onClick={toggleEditing}>Edit</button>
    </>
  );
};

This is going to fail, because current is null, since the component haven't re-rendered yet, and the input field is not yet rendered (and therefore can't be focused yet).

What is the right way to do this? I can use the usePrevious hook proposed in the React Hooks FAQ, but it seems like a painful workaround.

Is there a different way?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can use the useEffect hook to run a function after every render when isEditing changed. In this function you can check if isEditing is true and focus the input.

Example

const { useState, useRef, useEffect } = React;

const EditableField = () => {
  const [isEditing, setEditing] = useState(false);
  const toggleEditing = () => {
    setEditing(!isEditing);
  };

  const inputRef = useRef(null);

  useEffect(() => {
    if (isEditing) {
      inputRef.current.focus();
    }
  }, [isEditing]);
  
  return (
    <div>
      {isEditing && <input ref={inputRef} />}
      <button onClick={toggleEditing}>Edit</button>
    </div>
  );
};

ReactDOM.render(<EditableField />, document.getElementById("root"));
<script src="https://unpkg.com/react@16.7.0-alpha.2/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.2/umd/react-dom.production.min.js"></script>
  
<div id="root"></div>

over 4 years ago · Santiago Trujillo Relatório

0

I know the accepted answer covers the requested element in the above question.

But as an additional note, if you are using functional components, make use of React.forwardRef to pass down the reference to child components. It might be definitely useful for someone who refers to this question later on.

In a more cleaner way, you can write your child component which accept the ref as given below:

    const InputField = React.forwardRef((props, ref) => {
        return (
            <div className={props.wrapperClassName}>
                <input 
                   type={props.type}
                   placeholder={props.placeholder} 
                   className={props.className}
                   name={props.name}
                   id={props.id}
                   ref={ref}/>
            </div>
        )
    })
over 4 years ago · Santiago Trujillo Relatório

0

Or Simply use this component

import { FC, useEffect, useRef } from 'react'

export const FocusedInput: FC<JSX.IntrinsicElements['input']> = (props) => {

    const inputRef = useRef<null | HTMLElement>(null)
    useEffect(() => {
        inputRef.current!.focus()
    }, [])
    return <input {...props} type="text" ref={inputRef as any} />
}

over 4 years ago · Santiago Trujillo 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