Home > Software design >  How to focus a text field when the page gets loaded in React using createRef()?
How to focus a text field when the page gets loaded in React using createRef()?

Time:04-28

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

CodePudding user response:

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

CodePudding user response:

i don't know why it ain't working in your case but i copy-pasted your code and it ran successfully.. there is nothing wrong with it imo.

  • Related