When using the e.target.getAttribute() method in React, custom attributes may not be successfully retrieved

I am struggling with handling custom attributes in my changeHandler function. Unfortunately, React does not seem to acknowledge the custom "data-index" attribute.

All other standard attributes (such as name, label, etc.) work fine.

What could be the issue here?

Here is my input field:

  <Input
    name="test"
    label="test 1"
    data-index="0"
    value={values.test}
    onChange={handleInput}
  />

In my changeHandler function (the data-index attribute remains null):

  const handleInput = (e: any) => {
    const { value } = e.target;
    const dataIndex = e.target.getAttribute('data-index');
    setValues({
       ...
    });
  };

UPDATE:

I discovered that when I check e.target.attributes, it shows the following.

NamedNodeMap {0: aria-invalid, 1: id, 2: name, 3: type, 4: class, 5: value, aria-invalid: aria-invalid, id: id, name: name, type: type, class: class, …}
0: aria-invalid
1: id
2: name
3: type
4: class
5: value
length: 6

The data-index attribute is completely ignored. What could be causing this?

Answer №1

To access them, you can utilize e.target.dataset. However, my suggestion would be to follow a more React-oriented approach.

<TextField
    value={formValues.input}
    onChange={() => updateInput({ name, description, id: 0 })}
/>
const updateInput = ({ name, description, id }) => {
    setFormValues({
       ...
    });
};

Answer №2

To access the data-index attribute in React with Typescript, you can typecast the target element and then call the getAttribute method on it.

const handleInputChange: ChangeEventHandler<HTMLInputElement> = (e) => {
    const index = (e.target as HTMLInputElement).getAttribute('data-index');
};

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

Error: Unable to locate Angular2 Custom Service

I have implemented a custom service to populate a list of people in my HTML. Below is the code for my custom service: app.peopleListService.ts import { Injectable } from '@angular/core'; import { Person } from "../model/peopleModel"; @Injecta ...

Utilizing Vue.js to set the instance global property as the default value for a component prop

Is it possible to access a global property from my vue instance when setting a default prop value in my component? This is what I would like to achieve props: { id: { type: String, default: this.$utils.uuid } } I attempted to use an arrow fun ...

A guide to organizing elements in Javascript to calculate the Cartesian product in Javascript

I encountered a situation where I have an object structured like this: [ {attributeGroupId:2, attributeId: 11, name: 'Diamond'}, {attributeGroupId:1, attributeId: 9, name: '916'}, {attributeGroupId:1, attributeId: 1, name ...

Vue.js - Error: Module not found: Cannot locate module 'lottie-vuejs'

I've been attempting to integrate lottie-vuejs into my project. After running the npm install command and following the steps outlined here, I encountered an issue. Unfortunately, I received the following error message: Module not found: Error: Can ...

Is there a way to utilize the map function to conditionally render elements in React and Firebase simultaneously?

My primary goal is to dynamically display a "Create profile" button if the user does not have a profile in Firebase, or an "Edit profile" button if the user already has a profile. I am able to successfully render the edit profile button by comparing the a ...

Problem with ngStyle: Error indicating that the expected '}' is missing

I encountered an error in the Chrome console when trying to interpret the code below: <div [ngStyle]="{'width': '100%'; 'height': '100%'; 'background-size': 'cover'; 'background-repeat&ap ...

Encountered a session.socket.io error: unable to find session using the provided key: connect.sid

So, I've been struggling with an issue for the past couple of days and I can't seem to figure it out. I've searched through various resources like this GitHub issue and Stack Overflow, but I still haven't found a solution. Here's m ...

Ensuring TypeScript's strict null check on a field within an object that is part of an

When using TypeScript and checking for null on a nullable field inside an object array (where strictNullCheck is set to true), the compiler may still raise an error saying that 'Object is possibly undefined'. Here's an example: interface IA ...

Navigating to a different page by clicking on a Table Row in react-table

Whenever I click on a table row, I am unable to navigate to another page. Although I have successfully implemented the getTdProps function to retrieve properties from the table row upon clicking on it, I'm facing difficulty in using 'react-route ...

Is there a way to fetch a random record from a MongoDb collection and exhibit all the fields of that haphazardly chosen document in HTML?

In my current project, I am fetching a random document from a MongoDB Collection and attempting to showcase all the fields of that document in HTML. Although I can successfully retrieve a random document, the issue arises when trying to display its fields ...

When transferring files to the src/pages directory in Next.js, the custom _app and _document components are not recognized

The documentation for Next.js mentions that the src/pages directory can be used as an alternative to /pages. However, I encountered a problem when moving my custom _app.tsx and _document.tsx files into the src folder, as they were being ignored. If you cr ...

Transfer the Vue query parameter from the current route to the router-link

Why is it so challenging to detect and pass query parameters in Vue components? I'm trying to access the router from my component, but nothing seems to be working. How can I achieve this? <router-link :to="{ path: '/', query: { myQue ...

Crashes within an HTML5 Canvas

Having recently started to explore Javascript and working with canvas elements, I've encountered a roadblock when trying to implement collision detection for the canvas walls. Typically, I have a small square drawn on the canvas that I can move aroun ...

Attempting to iterate over elements within an object labeled as strIngredients 1-15

event.preventDefault(); $('#mainContent').empty(); $.ajax({ url: randomDrinksURL, method: 'GET' }).then(function (response) { console.log(response); var mainContent = $('#mainContent&ap ...

How does NextJS effectively perform interpolation on the code provided?

I've been curious about the way NextJS distinguishes between JSX and JS in the code snippet below. It seems straightforward, but I'm interested in what's happening behind the scenes. Specifically, I'm puzzled by how JSX is successfully ...

Harness the power of the ioHook Node.js global native keyboard and mouse listener within your Browser environment

I'm dealing with a challenging issue that seems to have no solution due to security limitations. However, I'm reaching out to you as my last hope to find a workaround. For my project, I require a system that can monitor user mouse and keyboard a ...

Iteratively traverse the object to establish connections between parent and child elements

I've been working on creating a recursive function with some guidance I received here: looping through an object (tree) recursively The goal is to traverse the object 'o' and generate a new one where each key is associated with its parents ...

Determine the dimensions of a div element in IE after adjusting its height to auto

I am currently working on a JavaScript function that modifies the size of certain content. In order to accomplish this, I need to obtain the height of a specific div element within my content structure. Below is an example of the HTML code I am dealing wit ...

"AngularJS offers a unique way to include alternative text in placeholders and titles using

I need to implement an input field (<input..>) with a placeholder and title for tooltip that functions in the following way: There is a variable called "myString" which can either be undefined/empty or contain a string. When empty, a default string ...

Explore various domains using the material-ui autocomplete feature

I'm currently working with material-ui and autoComplete in ReactJS to search within a single domain. How can I modify it to search across multiple domains? In addition, I would like to include the customerSurname field. Currently searching based on ...