Codehan25
Codehan25

Reputation: 3014

React doesn't get custom attribute with the e.target.getAttribute() method

I'm trying to process custom attributes in my changeHandler. Unfortunately, React doesn't recognize the custom "data-index" attribute.

All other standard attributes (such as name, label, etc.) are recognized.

What am I doing wrong?

My input field:

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

My changeHandler (data-index is always null here):

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

UPDATE:

I found out that e.target.attributes outputs 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

My data-index attribute is not recognized at all. Why?

Upvotes: 0

Views: 641

Answers (2)

2mighty
2mighty

Reputation: 179

If you are using React + Typescript, you can typecast the target element and then use the getAttribute property on it.

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

Upvotes: 0

Prime
Prime

Reputation: 2849

You can access them via e.target.dataset. But I recommend you to apply more React-like way.

<Input
    value={values.test}
    onChange={() => handleInput({ name, label, index: 0 })}
/>
const handleInput = ({ name, label, index }) => {
    setValues({
       ...
    });
};

Upvotes: 1

Related Questions