Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.textInput.focus is not a function - React

I have FormControl for password input with icon that toggles the mask, so u cant see the characters you are inputting. But whenever I toggle this mask I also want to re-focus the input field.

<FormGroup
    className="input-text input-text--password"
    controlId={id}
    validationState={submitFailed && touched && error ? 'error' : validationState}
  >

    <FormControl
      {...input}
      disabled={disabled}
      className="input-text__input"
      autoFocus={autoFocus}
      type={maskEnabled ? 'password' : 'input'}
      onChange={this.handleFormControlChange}
      maxLength={maxLength}
      ref = { ref => this.textInput = ref }
    />
    <div
        className={'input-text__button ' + (maskEnabled ? 'mask-enabled' : 'mask-disabled')}
        onClick={this.handleToggleInputMode}
    />

... I use this method to focus:

handleToggleInputMode() {
  let newMaskEnabled = !this.state.maskEnabled;
  this.setState({maskEnabled: newMaskEnabled});
  this.textInput.focus();
}

But i keep getting error

Uncaught TypeError: this.textInput.focus is not a function

So i tried to put it in ComponentDidMount but then the whole componend stopped responding (didnt accept any char I typed in). What am i missing?

like image 947
Dlike Avatar asked Sep 29 '17 08:09

Dlike


1 Answers

Please check working demo

 class App extends React.Component {
  componentDidMount() {
    this.textInput.focus();
  }
  render() {
    return (
      <div>
        <div>
          <input
            defaultValue="It will not focus"
          />
        </div>
        <div>
          <input
            ref={(input) => { this.textInput = input; }}
            defaultValue="with focus"
          />
        </div>
      </div>
    );
  }
}
    
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>
<div id="app"></div>

Edit

for FormControl you should use inputRef as per documentation

<FormControl inputRef={ref => { this.input = ref; }} />
like image 86
Jigar Shah Avatar answered Oct 04 '22 04:10

Jigar Shah