Dan Dan - 1 year ago 212
React JSX Question

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.

<input type="text" maxLength="4" />
<input type="text" maxLength="4" />
<input type="text" maxLength="4" />

the second question is how can I make input accept only numerical values when type="text"?

Answer Source

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) {

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download