Differentiating between two text fields: a step-by-step guide

I need assistance with setting up a form with 4 text fields for entering a 4-digit code sent to a phone. How can I automatically switch to the next field when a number is entered and ensure that only numbers are accepted? I will include a screenshot along with my code base. https://i.sstatic.net/tFvRu.png

// flow
import React, { useRef } from 'react';
import { signup } from '../../assets/images';
import FormDiv from '../shared/Sign-in-div';
import ImageDiv from '../shared/Image-div';
import { Nunito32, Nunito20 } from '../shared/nunito/nunito';
import ImageContainer from '../shared/image-container';
import OtpField from '../shared/otp-field';
import PinkButton from '../shared/button-color-pink';

let [fieldOne, fieldTwo, fieldThree, fieldFour] = useRef(null);

const onChange = (field) => {
  field.current.focus();
};

const SignUpVerification = () => (
  <div style={{ display: 'flex' }}>
    <FormDiv style={{ textAlign: 'center' }}>
      <Nunito32
        style={{
          display: 'inline-block',
          textAlign: 'center',
          marginRight: 236,
          marginLeft: 200,
        }}
      >
        Verify your mobile number by entering the code we sent you
      </Nunito32>
      <div style={{ flexDirection: 'row' }}>
        <OtpField
          ref={(input) => {
            fieldOne = input;
          }}
          style={{ marginRight: 10.5 }}
          onChange={() => onChange(fieldTwo)}
        />
        <OtpField
          ref={(input) => {
            fieldTwo = input;
          }}
          onChange={() => onChange(fieldThree)}
          style={{ marginRight: 10.5 }}
        />
        <OtpField
          ref={(input) => {
            fieldThree = input;
          }}
          onChange={() => onChange(fieldFour)}
          style={{ marginRight: 10.5 }}
        />
        <OtpField
          ref={(input) => {
            fieldFour = input;
          }}
          style={{ marginRight: 10.5 }}
        />
      </div>

      <PinkButton style={{ marginTop: 75 }}>Continue</PinkButton>
      <Nunito20>Send again</Nunito20>
    </FormDiv>
    <ImageContainer>
      <ImageDiv bg={signup} src={signup} alt="logo" />
    </ImageContainer>
  </div>
);

export default SignUpVerification;

I am encountering two errors stating that fieldOne is created but not used and an "Invalid hook call" error. Hooks should only be called within function components. This issue may occur due to the following reasons:

Answer №1

Wouldn't it be better to refresh the page after updating the state?

Answer №2

Managing focus can be effectively accomplished using Refs in React. The concept involves assigning refs to input fields and then, in the onChange event handler, verifying if the user has entered 3 digits before shifting focus to the next input.

To illustrate this approach, I have developed a demo on codesandbox demonstrating how it operates.

Answer №3

If you are utilizing React JS, you have the option to move ahead with React Refs and the DOM for selecting nodes and managing focus programmatically. Below is a sample implementation. You can find the implementation here.

class App extends React.Component{
  componentDidMount(){
    this.fieldOne.focus();
  }
  onChange(field) {
  field.focus();
  }
  render() {
    return(
      <div>
        <input
          onChange={() => this.onChange(this.fieldTwo)}
          ref={(input) => { this.fieldOne = input; }} 
          placeholder="First Field" 
        />
        <input 
          onChange={() => this.onChange(this.fieldThree)}
          ref={(input) => { this.fieldTwo = input; }} 
          placeholder="Second Field" 
        />
        <input 
          onChange={() => this.onChange(this.fieldFour)}
          ref={(input) => { this.fieldThree = input; }}  
          placeholder="Third Field" 
        />
        <input 
          ref={(input) => { this.fieldFour = input; }} 
          placeholder="Fourth Field"
        />
      </div>
    );
  }
}
    
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.1/react-dom.min.js"></script>

 <div class="container-fluid" id="main">
  <div class="row">
    <div class="col-xs-12">
      <div id="root"></div>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Offsetting absolute elements in a horizontal landscape view

When I view my page on a mobile browser (tested on Android JB and iOS 6), it renders fine initially in both portrait and landscape modes. However, the issue arises when I switch from landscape to portrait - the absolute positioned divs are offset from thei ...

Ways to transfer information from a Redux state to a state in a React hook

I am facing a challenge in my react/redux app where I need to pass data from the state in redux to my react component's useState. I have attempted various solutions but nothing seems to work. Can anyone suggest an efficient way to tackle this issue us ...

Using React Material UI Autocomplete, disable OnInputChange function after choosing a value from the dropdown menu

Is there a way to prevent React Material UI from triggering onInputChange when an option is selected from the dropdown? I am facing an issue where the API is being retriggered after using the dropdown, which I am trying to avoid. <Autocomplete ...

Instructions for crafting a sliced circle with CSS3 and HTML5

I need assistance creating a unique sliced circle interface where each slice can be clicked to execute different commands, similar to buttons. The design specifications for the slices are as follows: 2 Circles: Main Outer circle and inner circle (half ...

The error message "webpack command not found" appeared in the terminal

I am working on a project using React with Django. When I try to run npm run dev, I encounter an error message. The error message reads: sh: 1: webpack: not found npm ERR! Linux 4.4.0-197-generic npm ERR! argv "/usr/bin/nodejs" "/usr/bin ...

Tips for ensuring an image remains consistently positioned alongside another element

I have a request - In my code, I have multiple h2 headings that I want to display with an image of the Orioles Logo on both sides. There are about 100 of them, and now I need to change all of them to show the Ravens Logo instead. Doing this manually would ...

Obtaining two divisions that simultaneously display partials in a parallel manner

It's proving difficult to align two divs containing rendered partials side by side within a form. Strangely enough, when I replace the divs with plain text, they respond perfectly to my style changes. However, as soon as I include the render code, the ...

When hovering over slick text, it becomes hidden because of non-responsive CSS. Are there any solutions to make it responsive?

I can't seem to get the on-hover dates to appear, even though they are rendered when inspecting the page. I suspect it could be related to a responsive CSS issue or class breaking. How can I resolve this? https://i.stack.imgur.com/jyEJb.png https:// ...

Screen the information passing through the Nivo Bar Chart

With react-table, I have successfully implemented data filtering but I am looking to enhance the dynamism of the filter. The current challenge lies in filtering the data displayed on a graph to make it more meaningful. I want to group products from the sam ...

Maintain a fixed element and enable the rest of the elements to scroll as the mobile browser address bar collapses while scrolling upwards

Currently facing a challenge where I want the background image to remain static while the address bar and content underneath scroll up. The image occupies 90% of the view height, and although I've prevented it from resizing and jumping when the addres ...

What could be the reason my CSS and Javascript animation is not functioning properly?

Currently working on creating a dynamic animation menu using CSS and Javascript, but encountering some issues. The concept involves having a menu with initially hidden opacity (using CSS), which becomes visible when the hamburger menu is clicked, sliding i ...

Establishing the defaultValue for a TextField component within the Material UI library in a React application

Currently, as I work on my React JS application, I am retrieving data asynchronously from the server and displaying the values in a TextField. While this method is functional, I find myself dissatisfied with it. The Existing Approach class TestComponent ...

Change a space-separated string containing coordinates into an array of JavaScript objects

Here is a string separated by spaces: const coordinates = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604" Now, we want to convert it into an array of objects: const coordinatesArray = [ { lat: 42.44492, lng: 75.637764 }, { lat: 42.4455 ...

Are the nav, footer, header tags not functioning correctly?

Hi everyone, I'm a newcomer to StackOverFlow! I have a question about the necessity of tags like Nav, footer, header, etc. Do they serve any purpose other than indicating what each section is about? I've heard they might be good for SEO rankings ...

Issue with Checkbox Element's Margin CSS Not Being Applied

Hello everyone, I'm feeling a bit puzzled as to why the margin in my CSS isn't applying correctly to the checkbox element. Below is an example of the code I'm using: HTML: <div class="panel"> <input id="bodytype-checkbox" ...

The disabled functionality of AddCircleIcon in Material UI seems to be malfunctioning

The AddCircleIcon button's disabled functionality is not working, even though the onClick function is functioning properly. Even when directly passing true to the disabled property, it still doesn't work. I am in need of assistance to resolve thi ...

What is the method for moving one div above or below another div using the scroll bar?

Here's the scenario I'm facing: I have rows with buttons that, when clicked, reveal a set of options. The challenge is that depending on where the row is located on the page, the settings need to open either above or below the button. When the b ...

Can you have nested objects in Redux state - is it a good idea?

Hey there, I'm new to Redux and still trying to figure things out. My question is about updating nested object values in the reducer - is it possible or even optimal? And if so, how can you achieve this? const initialState = { banner: { backgro ...

How to extract the id instead of the value in ReactJs when using Material UI Autocomplete

I am utilizing Material UI Autocomplete to retrieve a list of countries, and my objective is to capture the selected country ID in order to send it back to the database. <Autocomplete options={this.state.countries.map(option => option.name_en + ` ...

Left-aligned Bootstrap carousel design

Recently, I've been working on tweaking this code to make it Bootstrap 4 compatible and left aligned. However, I'm encountering two persistent issues that I can't seem to resolve: The right side keeps getting cut off even though I intended ...