Elcid_91
Elcid_91

Reputation: 1681

ReactJS Cannot get input autofocus to work

Exploring ReactJS and attempting to create a base component called "TextField". If the focus property exists then the field is supposed to set focus after the component mounts. I have the following code but I can't track down why the setting the focus does not work:

import React, { Component } from "react";
import "./inputs.css";

export const TextField = class TextField extends Component {
    constructor(props){
        super(props);
        this.myRef = React.createRef();
    }
    componentDidMount(){
        if(this.props.focus){      
            this.myRef.current.focus();
        }
    }
    render(){
        var errid = this.props.id + "_errmsg";
        var labelStyle = "w3-label-font";
        var inputStyle = "w3-input w3-border w3-light-grey w3-round";
        return(
            <div>
                <label className={labelStyle}><b>{this.props.label}</b></label>
                <input className={inputStyle} type={this.props.type} id={this.props.id} name={this.props.name} ref={this.myRef}/>
                <div id={errid} className="error-msg"></div>
            </div>
        );
    };
}

Upvotes: 0

Views: 56

Answers (2)

pegasuspect
pegasuspect

Reputation: 1031

Your problem could be at rendering.

/*
  Write JavaScript/React code here and press Ctrl+Enter to execute.

  Try: mountNode.innerHTML = 'Hello World!';
   Or: ReactDOM.render(<h2>Hello React!</h2>, mountNode);
*/
class TextField extends React.Component {
  constructor(props){
    super(props);
    this.myRef = React.createRef();
  }
  componentDidMount(){
    this.myAwesomeInput.focus()
  }
  render(){
    var errid = "_errmsg";
    var labelStyle = "w3-label-font";
    var inputStyle = "w3-input w3-border w3-light-grey w3-round";
    return(
      <div>
        <label className={labelStyle}><b>blabla</b></label>
        <input className={inputStyle} ref={(input) => { this.myAwesomeInput = input; }}/>
        <div id={errid} className="error-msg"></div>
      </div>
    );
  }
}

// following won't work 
//ReactDOM.render(
//  new TextField().render(),
//  document.getElementById('container')
//);

// This works!
ReactDOM.render(
  <TextField />,
  document.getElementById('container')
);


Check out this fiddle:
https://jsfiddle.net/e7mL9vd6/2/

Upvotes: 0

Shmili Breuer
Shmili Breuer

Reputation: 4147

You can just add autoFocus to the input you want to auto focus.

 <input autoFocus />

Upvotes: 1

Related Questions