Search code examples
javascriptreactjsace-editor

Using React, click the first input show the second input, how to auto focus to the second input?


Using react, i click the first input to show the second input(react-ace editor), how to make the second input(react-ace editor) automatically gets focus and the first input lost focus ?

 constructor(props) {
    super(props);

    this.state = {
        hidden: true,
        value: props.value
    };
}
...
 render() {

 return <div className="form-group">
     <Input  onClick={() => this.showEditor()}  onChange={() => false} value={this.props.value}/>
     <div className={classNames({'hidden': this.state.hidden})}>
     <ReactAceEditor
        onLoad={(editor) => {
          editor.focus();
        }} 
     />
   </div>
   </div>
}

Solution

  • Pass focus={true} to the AceEditor, and don't render it until the input is clicked. Once the AceEditor is rendered, it will get focused and thus cause the input blur.

    Have tested and it works.

    <input onClick={() => this.setState({ show: true })}/>
            { 
              this.state.show &&
                <AceEditor
                  focus
                  mode="javascript"
                  theme="monokai"
                  onChange={(newValue) => this.code=newValue}
                  name="UNIQUE_ID_OF_DIV"
                  editorProps={{$blockScrolling: true}}
                />
            }