Effortlessly navigate between Formik Fields with automated tabbing

I have a component that validates a 4 digit phone code. It functions well and has a good appearance. However, I am struggling with the inability to autotab between numbers. Currently, I have to manually navigate to each input field and enter the number. Is there a way to achieve this using Formik Field?

Here is an excerpt of my code:

<Formik
  onSubmit={values =>
    VerifyGarageFunc({ code: values.code.join(''), requestId: PhoneCodeData.data }, data.showModal)
  }>
  {({ values, handleChange, handleSubmit }) => (
    <form onSubmit={handleSubmit}>
      <FieldArray
        name="code"
        render={arrayHelpers => (
          <div className={styles.inputWrapper}>
            {values.code.map((item, index) => (
              <div key={index}>
                <Field
                  name={`code.${index}`}
                  type="text"
                  component={CustomInput}
                  onChange={handleChange}
                  value={values.code[index]}
                />
              </div>
            ))}
          </div>
        )}
      />
      <LoginActionButton onSubmit={handleSubmit} text={'Send'} />
      <FieldArray />
    </form>
  )}
</Formik>

I attempted to use https://www.npmjs.com/package/react-auto-tab but it seems to only work with <input/> and does not function properly with Formik Field.

P.S. My application is built with Next.js and React.js

Answer №1

If you're looking for a hook-based solution, consider trying out the React Pin Input Hook library. It handles the logic without dictating the display.

To implement this, create a new component called PinInput and set up a new field using the formik hook primitives.

I've provided an example on codesandbox here: CodeSandbox Example. Please note that the code in the sandbox may not match your specific components exactly, but it should give you a close approximation of what you need.

import React from 'react'
import { useField } from 'formik'
import { usePinInput } from 'react-pin-input-hook'

export const PinInput = (props) => {
     const [field, meta, helpers] = useField(props)
     const { fields } = usePinInput({
       values: field.value,
       onChange: (values) => {
         helpers.setValue(values)
       },
    })
    
    return fields.map((fieldProps, index) => 
      <CustomInput key={index} type="text" {...fieldProps} />
    )
}

In your main file, simply integrate the Pin Input into your Formik form. If you're using the Form component from Formik, you won't have to manually bind the onSubmit event - the button can just be of "submit" type:

<Formik
  onSubmit={values =>
    VerifyGarageFunc({ code: values.code.join(''), requestId: PhoneCodeData.data }, data.showModal)
  }>
     <Form>
        <PinInput name="code" />
        <LoginActionButton type="submit" text={'Send'} />
     </Form>
</Formik>

Keep in mind that the library requires your CustomComponent to attach a ref to the input element. Make sure your component supports the necessary events like onBlur, onFocus, onChange, and onKeyDown.

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

Executing a function after the completion of another

Here is my function: function functionName($results) { //do some stuff disableSave() } When this function runs, I want to call the enableSave() function. How can I achieve this? I attempted to pass the function as a callback but I am unsure wher ...

An abundance of choices in the React dropdown

What is the most efficient approach for managing a dropdown with millions of options? In my scenario, there are over a million users and I need to select one at a time. One option is to make asynchronous calls for each letter typed to filter the users. A ...

separating kids with selectors

What is the recommended method for adding borders between children of various elements within a div? In the example below, there should be borders between p,div and div,img. <div id="list"> <p>child 1</p> <div>child 2</ ...

Incorrect legend colors in Highcharts pie chart

[![enter image description here][1]][1] There seems to be an issue with the Pie-Chart where the Slice color and the Legend color do not match when the color is set using className. This problem does not occur with some other charts. If you look at the co ...

What is the best way to incorporate Ajax into a Rails application?

Check out the Webpage Design I am currently working on a Todo List that includes various Todo Items. Each incomplete task has a button called "Mark Item as Done" next to it, which triggers the button_to method when clicked. I am facing challenges in imple ...

Is it acceptable to assign a value to exports.new?

In my venture with Node.js and Express, I am aiming for simplicity. Drawing from my experience with Rails, I am following the RESTful structure typical in Rails applications. In setting up my controllers (or routes), I want them to resemble this: // route ...

Angular Fragmentary Perspective

I have a lengthy form in angular that I am currently working on. I'm wondering if there is a way to divide it into multiple views and then link each of them back to the main view. <div class="container"> <div class="row" id="part1"> ...

directive still running despite attempting to stop the service

In my modal window, there is a directive that utilizes a service to make HTTP requests at regular intervals using $interval. However, even after closing the modal window, the service continues to run and make requests every 30 seconds. Is there a way to ...

How to Link to a new page using current page slugs in NextJS?

My current URL looks like this: http://localhost:3000/courses/italian/dynamic/lessons/wenC6hgETeMHSiFNabvk http://localhost:3000/courses/[language]/dynamic/lessons/[lessonID] I am searching for a simple way to access the .../exercises page. All I want to ...

The functionality of Bootstrap pagination is incompatible with the angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.js library

After reading through this discussion, I have found that in order to resolve an issue, I need to utilize a newer version of ui-bootstrap-tpls.js. However, the downside is that this disables the functionality of bootstrap pagination, which only works with a ...

I encountered no response when attempting to trigger an alert using jQuery within the CodeIgniter framework

Jquery/Javascript seem to be causing issues in codeigniter. Here is what I have done so far: In my config.php file, I made the following additions: $config['javascript_location'] = 'libraries/javascript/jquery.js'; $config['javas ...

How can a JavaScript function be imported into a React component from a location outside the src folder?

I have a utility function in my JavaScript utils.js file within the Django static files. I am looking to make this file accessible for use with React as well. I would like to import this file along with its functions into a React component. Here is an ex ...

Include two additional elements for action in a list

In my React project, I've created a list with the following elements: Avatar Text Edit icon Delete icon I managed to set up the structure successfully up until the delete icon. Now, how can I properly add it without overlapping the edit icon? Both ...

Encountered an error while configuring AWS Amplify using Amplify.configure(awsconfig)

I've encountered an issue while using the amplify cli in conjunction with my NextJs app. It seems like there might be a misconfiguration as I'm receiving the following error when attempting to query data: [WARN] 32:17.454 DataStore - Data won&ap ...

Is it considered best practice to incorporate the Box component within the Grid component in MUI?

This code snippet is just an illustration. My initial implementation functions correctly, but I am seeking to enhance it further. Sample code snippet: <Grid container justifyContent="space-between"> <Box display = "flex"> ...

Creating a hover effect on a specific area of a map is a useful technique

Can someone please help me create a hover effect for areas in maps? Below is the code for the map. Thank you in advance! Here is the image. <img src="[CR_kraje_1_úroveň_v1] (imported)" width="770" height="443" border="0" usemap="#map" /> &l ...

The Typescript error occurs when trying to assign a 'string' type to a 'SetStateAction<null>'

For my project, I am delving into creating a global context using TypeScript. As a newcomer to TypeScript, I found a helpful guide in this blog post (). Despite following the outlined steps, I keep encountering an error message saying "Type 'string&ap ...

The element is inferred to have an 'any' type due to the inability to use a 'string' type expression to index the 'Palette' type

Encountering an issue: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Palette'. No index signature with a parameter of type 'string' was found on type &ap ...

Creating unique geometric designs with three.js

Attempting to construct a polygon in three.js and here is the code used for it. function DeployZone(coordinatesList) { // Forming the polygon Shape { var material = new THREE.MeshLambertMaterial({ color: 0x00ffcc }); var faces = [0, 1, 2, 3, 4] ...

javascript utilizing underscorejs to categorize and aggregate information

Here is the data I have: var dates = [ {date: "2000-01-01", total: 120}, {date: "2000-10-10", total: 100}, {date: "2010-02-08", total: 100}, {date: "2010-02-09", total: 300} ]; My goal is to group and sum the totals by year like this. ...