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

326
Visualizações
How to focus a text field when the page gets loaded in React using createRef()?

I'm able to achieve this functionality only when i invoke my function manually. Used componentDidMount() in my case to bring focus on the input element when the page loads, but no luck. Sharing my code -

import React, { Component } from 'react'

export class RefsDemo2 extends Component {
  constructor(props) {
    super(props)
    this.textInput = React.createRef();
    // this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput(){
      this.textInput.current.focus();
  }

  componentDidMount(){
    this.textInput.current.focus();
  }

  render() {
    return (
      <div>
          <input type="text" ref={this.textInput}></input>
          {/* <input type="button" onClick={this.focusTextInput} value="Focus this input"/> */}
          {/* <input type="button" ref={this.focusTextInput} value="Focus this input"/> */}
      </div>
    )
  }
}

export default RefsDemo2
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

please use Can Try This -

import React, { Component,useEffect } from 'react'

export class RefsDemo2 extends Component {
  constructor(props) {
    super(props)
    this.textInput = React.createRef();
    // this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput(){
      this.textInput.current.focus();
  }

  componentDidMount(){
    this.textInput.current.focus();
  }

  useEffect(()=>{
        document.getElementById("myInput").focus();
  },[])

  render() {
    return (
      <div>
          <input id="myInput" type="text" ref={this.textInput}></input>
          {/* <input type="button" onClick={this.focusTextInput} value="Focus this input"/> */}
          {/* <input type="button" ref={this.focusTextInput} value="Focus this input"/> */}
      </div>
    )
  }
}

export default RefsDemo2
about 4 years ago · Juan Pablo Isaza Relatório

0

Please, avoid using document.getElementById or any DOM query directly as the other answer suggested. This should work (as it is coming from the oficial documentation):

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }
  
  componentDidMount() {
    this.focusTextInput();
  }    
  
  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

As you can see, you were pretty close, but you needed to also bind the function to focus the input with ref before using it.

Edit: This is the stackblitz example working Stackblitz and editor Editor

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