skip to Main Content
const onMenuItemClick = (event) =>{
    console.log("onMenuItemClick data-id",event.target.getAttribute('data-id'));
}

html (JSX) is like this below,

One parent div which has two children div

<div onClick={onMenuItemClick} data-id="show">
         <div className={styles['contextIconBox']}>
          <img src={btn_delete} className={styles['contextIcon']}/></div>
          <div className={styles['contextLabel']}> myarea</div>
         </div>
</div>

When cliking this div onMenuItemClick is called

However data-id is not fetched(data-id is null),

I guess maybe, this is becasuse onMenuClick is fired but event is not the parent div?

How can I get dhe data-id here?

2

Answers


  1. You’re nested DOM element is retrieving the onClick.

    Use currentTarget to get the DOM element from which the current event handler is attached.

    Or for more complex DOM setups, you might want to add a className to each menu-item and then use .closest('.menu-item') so search for the matching item.


    const Example = () => {
        
       const onMenuItemClick = (event) =>{
            console.log("Clicked on ", event.currentTarget.dataset.id);
            console.log("Clicked on ", event.target.closest('.menu-item').dataset.id);
        }
    
        return (
            <div>
                <h1>{'Example'}</h1>
                <div className='menu-item' onClick={onMenuItemClick} data-id="show">
                    <div className='contextIconBox'>
                        <em className='contextIcon' />
                        <div> myarea</div>
                    </div>    
                </div>
            </div>
        )
    }
    ReactDOM.render(<Example />, document.getElementById("react"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
    <div id="react"></div>
    Login or Signup to reply.
  2. You can use currentTarget instead of target

    const onMenuItemClick = (event) =>{
        console.log("onMenuItemClick data-id",event.currentTarget.getAttribute('data-id'));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search