Home > Mobile >  Why is e.target.value undefined
Why is e.target.value undefined

Time:10-25

Why is e.target.value undefined when logged to the console in this very simple component? The value is defined within the element so I don't understand why e.target returns the value as undefined.


const NavBar = () => {

    const handleClick = (e) => {
        console.log(e)
    }
    
    return (
        <div id="navbar">
                <nav >
                <div >
                <button  type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                    <span ></span>
                </button>
                <div  id="navbarNavAltMarkup">
                    <div >
                    <a  aria-current="page" href="/home" onClick={(e) => handleClick(e.target.value)}>Home</a>
                    <a  aria-current="page" value={1} onClick={(e) => handleClick(e.target.value)} > About</a>
                    <a  aria-current="page" value={2} onClick={(e) => handleClick(e.target.value)} > Contact</a>
                    </div>
                </div>
                </div>
            </nav>
        </div>
    )
}

export default NavBar

CodePudding user response:

a elements don't have the value attribute. That why you get undefined.

CodePudding user response:

There's a difference between e.target and e.currentTarget use the latter to reference the element you attached the event listener to:

It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.

— MDN about Event.currentTarget

As other answers mention, use data-* attributes for custom attributes like:

<a href=".." data-value="value"></a>

And read it with:

e.currentTarget.getAttribute("data-value")

CodePudding user response:

a tag doesn't have a value property

You can use getAttribute

e.target.getAttribute('value')

Although, you should use data-value and get it through e.target.dataset.value

Right now you are adding unexisting attributes

  • Related