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

Tips for preserving scroll location on Angular components (not the window) when navigating

My current layout setup is like this: https://i.sstatic.net/hOTbe.png In essence <navbar/> <router-outlet/> The issue I'm facing is that the router-outlet has overflow: scroll, making it scrollable (just the outlet section, not the ent ...

Fetching all data from a SQLite database in a Listview using React Native

I have been utilizing the library found at https://github.com/andpor/react-native-sqlite-storage in my react native project. To retrieve a single row from the database, I use the following code: db.transaction((tx) => { tx.executeSql('SEL ...

Learn how to trigger the keydown function in VUE programming

I am trying to create a method that will be triggered whenever any key on the keyboard is pressed, regardless of where the focus is. I want to be able to determine which key was pressed in this method. Currently, I have set up an event listener for keydow ...

"activeStyle" attribute consistently being implemented on links within pagesindex.js

Just starting out with Gatsby/React and web development in general, so apologies if this is an easy fix. I'm facing an issue that I can't seem to solve. Currently, I'm working on my website's header and trying to create links to naviga ...

What is the best way to apply a unique style (such as adding a bottom border) to all list items

Currently, I am utilizing React Material components with a List that is internally represented as ul li elements. My goal is to apply a style to all li elements by adding a bottom border. One approach is to include the className={classes.sideBar__listItem_ ...

Sending Data from Browser to Node.js using Ajax

I've been struggling to send an AJAX post request to my Node server built with Express for a while now. Despite reading various solutions on similar issues, I couldn't figure out which files to edit. Initially, I attempted using `http.createServe ...

Creating an Interactive Menu System with Nested Options in Angular 2

I have a JSON structure that I need to transform into a menu with sub-menus based on the value of the sub-menu_location field. Here's an example: { "data": [ { "menu_name": "Primary Operations", "enabled": true, "sub-menu_lo ...

One way to increment a database attribute by one is to send a GET request to the database using Reactjs

I am currently working on a Mernstack project and I have a model called Events. Each Event has attributes such as title, description, startingDate, and closingDate. One of the functionalities I want to implement is allowing users to indicate that they are ...

What is the best way to collapse additional submenus and perform a search within a menu?

Whenever a sub-menu is activated, only the current sub-menu should be open while the others remain closed. I need the search function to be enabled on the text box and display all items containing the specified value while also changing the color of <a ...

Issues with the functionality of jQuery's .load() method are causing

I am encountering an issue for the first time. Inside ajax.html, I have the following code in the header: $(document).ready(function(){ $( "#result" ).load( "/loaded.html" ); }); In the same directory, there is a second page named loaded.html: <d ...

The Swiper example is not compatible with the default settings of Next 13

Swiper is not compatible with Next 13. Using the default React example of Swiper + 'use client' at the top of the page does not yield the expected results. To replicate the issue, follow these steps: Create a bare-bones Next 13 app using this ...

The Typescript SyntaxError occurs when attempting to use an import statement outside of a module, typically within a separate file that contains

I am currently developing a Minecraft bot using the mineflayer library from GitHub. To make my code more organized and reusable, I decided to switch to TypeScript and ensure readability in my project structure (see image here: https://i.stack.imgur.com/znX ...

Bringing in personalized data types using unique import aliases

Recently, I made changes to my Next.js project by upgrading it to TypeScript. One of the modifications I made was updating my import alias from @/* to @*. Below is the new configuration in my tsconfig.json. { "compilerOptions": { "targ ...

Failure of Styling Inheritance in Angular 2 Child Components from Parent Components

My Parent Component utilizes a Child Component. I have defined the necessary styles in the Parent CSS file, and these styles change appropriately when hovering over the div. However, the Child Component does not inherit the styling classes of the Parent Co ...

Different methods to avoid using $scope.$watch in a directive when dealing with an undefined variable

As I work on my angularjs application, I find myself utilizing directives for reusable UI elements across different pages. However, I encounter a challenge when a directive depends on a value from a promise. In such cases, I have to employ $scope.$watch al ...

The value of $parent.$index will consistently be 0 in all cases

I am currently dealing with a nested ng-repeat situation where I am attempting to determine the parent's index. Due to the fact that it is being arranged post-process, the standard ng-repeat="(step_index, step) in flow" method is not working for m ...

Compilation issues encountered while running TypeScript in Dockerfile

I am encountering an issue with my Dockerfile during the TypeScript compilation step. Below is the snippet of code where it fails: FROM node:12 WORKDIR /usr/src/app # SETUP COPY package.json . COPY tsconfig.json . COPY src . RUN npm install -g yarn@^1. ...

The delete_node() function in jstree does not seem to be removing nodes

In my attempt to create a custom context menu for different nodes, I've managed to display different labels for clicks on folders or files. However, I am facing some challenges when trying to delete them. Take a look at my code snippet. Due to diffic ...

Apply a class to each consecutive element following the current one until reaching a child element with a

My goal is to apply a "bg-info" class using jQuery to all rows (tr) that come after odd rows with a child element of "test". The "bg-info" class should be removed when a row with a child element of "test" is encountered, and then re-applied when the next o ...

New updates are not appearing in the Azure app service for a React application when using GitHub actions

I have configured the Azure app service with default settings, and there are no warnings or errors during the build process. The deployment was successful, but the changes do not reflect in the production environment; it still shows the previous build. H ...