I have this simple code of a TextInput
that I want it to get focus when it first renders and on submits. However, it does not get focus at all.
render() {
return (
<TextInput
ref={(c) => this._input = c}
style={[styles.item, this.props.style]}
placeholder={"New Skill"}
onChangeText={(text) => {
this.setState({text})
}}
onSubmitEditing={(event) => {
this.props.onSubmitEditing(this.state.text);
this._input.clear();
this._input.focus();
}}
/>
);
}
componentDidMount() {
this._input.focus();
}
Two methods exposed via the native element are .focus() and .blur() that will focus or blur the TextInput programmatically.
To disable options on React Native TextInput, we can set the editable and selectTextOnFocus props to false . to set them both to false . Then we won't see any popup options displayed when we focus on the text input. editable set to false disables typing in the input.
React onBlur behaves just like the native JavaScript version of blur. Every time you get out of focus from the input field, the event will trigger. It doesn't matter if the value has changed or not, every time you get out of focus. The event will trigger.
To change the styling of TextInput placeholder in React Native, we can set the placeholderTextColor prop. to set the placeholderTextColor to 'red' to set the placeholder color of the input to red.
So my assumption is true. Try to focus is failed, this._input
doesn't contain anything when componentDidMount
called, because render
function still not called yet and no reference for it.
So the solution for now is delay it a little bit until render function already called.
Thats why wrap the code inside setTimeout
function quite helpful. Anyway i admit it, it is a little bit tricky. Would be great if someone find the better way.
componentDidMount() {
setTimeout(() => this._input.focus(), 250);
}
You can use autoFocus property of TextInput and set it to true. It will focus TextInput on componentDidMount automatically.I tested it and it's focusing input on both componentDidMount and onSubmitEditing.
render() {
return (
<TextInput
ref={(c) => this._input = c}
placeholder={"New Skill"}
autoFocus={true}
onChangeText={(text) => {
this.setState({text})
}}
onSubmitEditing={() => {
this.props.onSubmitEditing(this.state.text);
this._input.clear();
this._input.focus();
}}
/>
);
}
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