Which element is undefined in this scenario - the Event Object or the inputs?

While working on OTP verification in Reactjs, I encountered an error message when running my code:

Error: Cannot read properties of undefined (reading 'value')



import { useState, useEffect, useRef } from 'react'

import '../src/component.css'

export default function Component(){

  

  const[count,setCount] = useState(0);

  const inpRef = useRef([]);

  useEffect(()=>{

    

    setTimeout(()=>{

      setCount(count+1)

    },1000);

  

    const handleInput =(e,index)=>{

      const current = inpRef.current[index];

      let next = inpRef.current[index+1];

      let prev = inpRef.current[index-1];

      

     const expression = /^\d+$/

     const isValid = expression.test(e.target.value);

     

     if(!isValid){

       e.target.value = "";

       return;

     }

      if (e.target.value.length >1){

        e.target.value ="";

      }

     

    }

    

    inpRef.current.forEach((input,index)=>{

      input.addEventListener('input',handleInput.bind(null,index))

    })

   return ()=>{

     inpRef.current.forEach((input,index)=>{

      input.removeEventListener('input',handleInput.bind(null,index))

    })

   }

  },[])

  

  return(

    <>

    <p> Counter : {count}</p>

    <h4>Now enter the OTP</h4>

   

    <div className="whole">

    <h5>Send the OTP to your phone Number</h5>

     <div className="container">

    {[...Array(6)].map((_,index)=>{

      return <input className="text-field" type ="number"

      ref = {(ref) =>{

        inpRef.current[index] = ref;

      }} 

      key ={index}

      />

    })}

    </div>

    <button className ="btn">SUBMIT</button>

    </div>

    

    </>

    )


}

Can you help me troubleshoot why I am getting this error? I am trying to create an OTP verification page with 6 input boxes where the focus automatically shifts to the next input when a value is entered, and shifts back when the backspace key is pressed.

Answer №1

Your handleInput function has the arguments in the incorrect order. In this case, index is actually event and e is index. This is why e.target.value is returning undefined.

Please make the following change:

const handleInput = (index, e) => { ... }

For a clearer explanation, check out this codesandbox example.

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

What is causing my animation to jump when using the Web Animation API reverse() function?

I've come across various sources stating that when you call reverse() while an animation is playing, it should have the same effect as setting playbackRate to -1. However, in my case, using reverse() makes my animation behave erratically and jump arou ...

Passing data through multiple levels in Angular

Imagine you have a main component called A with a variable x inside it that you want to pass to a child component B. Using the @Input annotation makes this task simple. But what if component B has its own child component C? How can we successfully pass t ...

Bootstrap 3 with a dual sidebar layout positioned on the left side

I am currently working on a project where I need to create a fluid layout with a left sidebar. However, now I would like to add an expandable sidebar next to the existing one. Below is an image to illustrate my goal: Initially, the left sidebar contains a ...

Issue with vertical alignment of text inside select dropdown in Material UI Core

Take a look at the image. The text isn't centered in the text box like the other fields on the form. Dropdown Alignment Issue Below is my code snippet: <FormControl style={{ width: "80%" }} size="small"> <InputLabel htmlFor="Implement ...

Encountering installation issues with Next.js and experiencing a package failure with react.js during the installation process

Issue: Error encountered during Next.js installation, multiple installation failures reported including missing packages peema@DESKTOP-6UGCO8V MINGW64 ~/Documents/alert/peeapp $ next build The module 'react' was not found. Next.js requires that ...

Warning: The use of 'node --inspect --debug-brk' is outdated and no longer recommended

Encountering this error for the first time, please forgive any oversight on my part. The complete error message I am receiving when running my code is: (node:10812) [DEP0062] DeprecationWarning: `node --inspect --debug-brk` is deprecated. Please use `node ...

I'm looking for a tool or software that can automatically generate Unit test files for ReactJs

Is there a tool or software available that can automatically generate unit test cases for ReactJs applications? I am looking to find an automated tool that can create unit test cases and identify potential test scenarios - is there such a tool out there ...

Issue with routing in Next.js 13.4 - tailAdmin interface

I recently utilized a template from https://github.com/TailAdmin/free-nextjs-admin-dashboard. However, I'm encountering a 404 error when trying to access my new blog page. The path causing the issue is "/app/blog/[id].tsx" import React from "r ...

PHP code for sending email with attachment file

I have created an HTML form with the option to upload a file and send it to me via email. Additionally, I already have a PHP script that sends textbox values and text area values via email. Now, I would like the uploaded file from the form to be sent to m ...

The system has encountered an issue: "EntityMetadataNotFound: Unable to locate metadata for the entity named 'User

Just wanted to reach out as I've been encountering an issue with my ExpressJS app recently. A few days ago, everything was running smoothly without any errors. However, now I'm getting a frustrating EntityMetadataNotFound: No metadata for "User" ...

Angular UI Grid failing to properly display date formatting

Currently, I am using Angular's UI Grid to showcase multiple columns. However, I am facing an issue with formatting the date column. The date is being displayed as /Date(1451346632162-0000)/, and similar formats. I have attempted to apply filters in ...

Creating a React table with customizable columns and rows using JSON data sources

My query is this: What is the most effective way to dynamically display header names along with their respective rows? Currently, I am employing a basic react table for this purpose. As indicated in the table (2017-8, 2017-9, ....), I have manually entere ...

hover causing the table cell to act erratically

My table consists of three cells with widths of 30%, 40%, and 30% respectively. The table itself occupies 25% of its container, which can range from 1024px to 400px. The first cell contains a button labeled GALLERY. Upon hovering over the cell, the text c ...

How come my FormData POST request isn't being blocked by CORS policy?

I am facing confusion with one query: why does my POST request, which sends form data from a frontend hosted on a different origin to a backend hosted on a different origin, not get blocked by CORS policy? My Node.js code includes the following: const exp ...

Creating multiple versions of a website based on the user's location can be achieved by implementing geotargeting techniques

It may be a bit challenging to convey this idea clearly. I am interested in creating distinct home pages based on the source from which visitors arrive. For instance, if they come from FaceBook, I envision a tailored home page for FaceBook users. If they ...

What are some strategies I can implement to effectively manage different errors and ensure the app does not crash

I came across a variety of solutions for error handling. The key concept revolves around this explanation: https://angular.io/api/core/ErrorHandler Attempts were made to implement it in order to capture TypeError, however, the outcome was not successful: ...

Easily implement a wide variety of fonts in your web projects by dynamically loading hundreds of font

I am in possession of a directory called /assets/fonts containing a plethora of fonts that I wish to incorporate into a website in a dynamic manner. Users will be able to specify their font preferences, akin to a text editor. Individually assigning the fo ...

Is there a way to adjust the position of a Bootstrap 5 dropdown menu in real-time using javascript or jQuery?

Within my web app, I have implemented dynamically generated Bootstrap 5 dropdown menus that can sometimes be extensive. To optimize screen space usage, I am seeking a way to alter the offset computed by Popper.js through javascript. Unfortunately, I have e ...

Retrieving the chosen option from a drop-down menu using FormCollection in MVC

I need to extract the selected value from a drop-down list in my HTML form, which is posting to an action using MVC. How can I achieve this? Here is my HTML form: <% using (Html.BeginForm()) {%> <select name="Content List"> <% ...

Preventing AngularJS from Binding in Rows: A Solution

Currently, I am utilizing AngularJS version 1.5.3 and I am facing an issue with my services. I have two services - one that retrieves Area names and the other that fetches details for each Area. In my code, I first call the service to get the Area names an ...