Joseph Walsh
Joseph Walsh

Reputation: 76

React: e.target.? logs undefined

I am trying to setState to q.content. However, it logs as undefined and I'm not sure how I'm using e.target incorrectly. It logs q.name fine.

I have a button that onClick calls a function that sets the constants.

In the function I have:

  function handleDelete(e) {
    e.preventDefault();
    setDeleteItem(e.target.value);
    setConfirmModal(true);
    setDeleteContent(e.target.content);
    setDeleteName(e.target.name);
    console.log(e.target.content);
  }
<button
   onClick={handleDelete}
   value={q.id}
   name={q.name}
   content={q.content}
   >

But it just doesn't seem to work.

Upvotes: 2

Views: 43

Answers (2)

shurikation
shurikation

Reputation: 84

Try this to pass attribute value to the function:

function handleDelete(e) {
    console.log(e.target.getAttribute('content')) //'CONTENT!"
    setContent(e.target.getAttribute('content')) //set as state
}

<button
    onClick={handleDelete}
    content={'CONTENT!'}
></button>

Upvotes: 0

Sampson
Sampson

Reputation: 268424

Not all attributes are available as DOM properties. While you can call e.target.value, you cannot call e.target.content in like manner. Instead, you'll need to access the element's attributes to get that value. To do so, check the e.target.attributes object, or use e.target.getAttribute.

Upvotes: 2

Related Questions