I have two questions about input in react. Is there any way that I can make input automatically focus next field once reaching maxLength with react without using jquery.
<form>
<input type="text" maxLength="4" />
<input type="text" maxLength="4" />
<input type="text" maxLength="4" />
</form>
the second question is how can I make input accept only numerical values when type="text"?
Use the onChange event handler for this. When the user typed MAX_LENGTH (4 characters), the focus is set to the next element. React.findDOMNode gets the next DOM node corresponding to a React component. The focus method on the DOM node sets the focus.
handleTextChange(e) {
if (e.target.value.length <= MAX_LENGTH) {
this.setState({ value: e.target.value });
}
if (e.target.value.length === MAX_LENGTH) {
React.findDOMNode(this.nextComponent).focus();
}
}
The component JSX is:
<input value={this.state.value} onChange={this.handleTextChange} />
<input ref={c => this.nextComponent=c} />
The nextComponent is set in ref. The this.nextComponent
is used by React.findDOMNode to get the DOM node corresponding to the next component.
I faced some errors with the code above. so i changed it like below and it's working well.
handleTextChange1(e) {
if (e.length <= 1) {
this.setState({value: e})
}
if (e.length === 1) {
this.input2.focus();
}
}
and also in the TextInputComponent i have:
<TextInput
ref= {(input) => this.input1 = input}
selectTextOnFocus={true}
onChangeText={this.handleTextChange1}/>
<TextInput
ref= {(input) => this.input2 = input}
selectTextOnFocus={true}
onChangeText={this.handleTextChange2}/>
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