Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus next input once reaching maxlength value in react without jQuery and accept only numeric values

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"?

like image 325
kay Avatar asked Oct 02 '16 12:10

kay


2 Answers

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.

like image 145
vijayst Avatar answered Oct 26 '22 07:10

vijayst


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}/>
like image 20
Mahdieh Shavandi Avatar answered Oct 26 '22 09:10

Mahdieh Shavandi