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

Utilizing Nuxt Axios to assign response data to a variable will dynamically modify the content of the

async fetch() { try { console.log(await this.$api.events.all(-1, false)); // <-- Logging the first statement const response = await this.$api.events.all(-1, false); // <-- Assigning the result console.log(response); // <-- Lo ...

Encountering the error message "TypeError: setValue is not a function" while trying to pass it as a

Struggling to update the useState() variables by receiving input from a child component nested within another child component. However, encountering an error message when attempting to call either setItem() or setValue() functions from the useState() decla ...

Interested in accessing JSON data from another domain? CORS has got you covered

Over at localhost:8080/abc/v1/doc, I get some json data when accessed directly from the browser's address bar. Here are the response headers: Response Headers Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET, POST, OPTIONS Cont ...

Employing the powerful Math.pow() function within the setState() method

In this ReactJS code example, the goal is to update the value of a div element with every click of a button using the Math.pow() method. However, it seems that the method is not working as intended. Can someone explain why? The handlerButton function in ...

What is the best way to send props to a React component?

Sorry for the inconvenience of asking for help with finding an issue in my code, but I'm facing challenges while learning React. I am attempting to pass a variable named hashRoute to a component in react. However, every time I try to access the prop ...

Inserting a file read using Node.js into a MongoDB database

Recently, I came across a text file that contains the following data: title: A, alert: notice, desc: Starting title: B, alert: notice, desc: Process Step 1 and 2 Step 1 - Execute Step 2 - Log title: C, alert: notice, desc: "Ending" My goal is to insert ...

What is the process for implementing a click event and accessing the DOM within an iframe using react-frame-component?

I am working on using the react-frame-component to create an iframe. I am trying to bind a click event on the iframe and retrieve the DOM element with the id of "abc" inside the iframe. Can anyone guide me on how to achieve this? The code snippet provided ...

issue with data binding in ons-dialog

Utilizing an ons-dialog to display a popup prompting the user to sign up for a newsletter. I have set a 3-second timeout to prevent users from immediately closing the prompt without reading it or waiting. I aim to initially show the dialog with the ' ...

What is the most effective way to loop and render elements within JSX?

Trying to achieve this functionality: import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = {"0": "aaaaa"}; return ( ...

Updating image source dynamically with Flask

I am currently developing a face detection application using Flask. I aim to have the detected faces displayed in real-time on the HTML page. For the JavaScript aspect, I am utilizing getUserMedia to live stream camera images from the client to the server ...

Attempting to retrieve dynamically generated input fields and cross-reference them with structured length .json data

In the process of developing code, I've implemented a for loop to dynamically generate HTML input fields based on the length of some data in a .json file. My goal is to use jQuery to compare the text entered in each input field with the corresponding ...

Tips on using the Hover property in CSS for an element that includes both :after and :before properties

I've created a hexagon using CSS after and before properties, and now I'm attempting to add a glowing effect around the hexagon when hovering. It works perfectly for the center of the hexagon but not for the top and bottom points of the shape. ...

JavaScript code must be tailored to reference a JS file based on the specific environment, whether it be Production, Development, or staging

I need to determine which .js file to refer based on the URL of Prod, Dev, and QA environments. For Production URLs (domain.com and www.domain.com), I should refer to prod.js file. For Dev and QA URLs (dev.domain.com and staging.com), I should refer to s ...

Check the output of the ChildProcess after executing a shell command

I am currently running the ChildProcess function within a Nextjs API route and I am struggling to retrieve the value from it. const output = exec( "curl -s -v https://test.com/index.php", (err, stdout, stderr) => { if (err) { ...

larger breakpoints are always overridden by smaller breakpoints

Is there a way to prevent smaller breakpoints from overriding the styles of larger breakpoints? I've attempted the following: <Box mt={{ lg: 0, md: 2 }}></Box> Unfortunately, the styles specified for lg: 0 were overridden by the ones gen ...

How can data be passed from a directive to a controller in Angular?

I am currently working on implementing a directive pagination feature and I need to pass the current page number from the directive to a controller in order to run a specific function with this argument. However, I keep getting an 'undefined' err ...

Missing Bootstrap 3 Options Menu trip away

I created a table with 4 columns using the Bootstrap 3 grid system. Instead of utilizing the col-xs-* classes, which work well on mobile devices, I opted for the col-md-* classes. This decision was based on my preference to have larger and more visible ico ...

Align a child element to the top and another child element to the center within a flexbox column

Struggling with flexbox column and can't find a solution online! The problem: I have a full-height flex-column on the right side of my viewport with two elements (headset icon and hangup button). Trying to vertically align them - first element at top ...

I am experiencing difficulties with the PHP login form on MAMP as it is not loading properly, displaying only a

Having trouble with php not loading when I open my browser. Here is my database info: MySQL To manage the MySQL Database, you can use phpMyAdmin. If you need to connect to the MySQL Server from your own scripts, use these connection parameters: Host ...

Unable to extract attributes from a different model within Sails.js

I'm working on populating a customer model with attributes from the address.js model. However, when trying to post JSON using Postman, I keep getting a 500 Validation Error and struggling to pinpoint the cause of the issue. Any assistance would be gre ...