0

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>
        );
    };
}

2 Answers 2

1

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

 <input autoFocus />
Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.