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?
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; }} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With