Shah Alom
Shah Alom

Reputation: 1055

Javascript event.target does not output as expected in ReactJs component

Consider the below ReactJs component:

import React from 'react';

const TestOptions = (props) => (
    <li className={props.className} onClick={(event) => props.clickTestOptions(event)}>
        {
            React.createElement(
                'div',
                {
                    className: 'opt-wrap',
                    dangerouslySetInnerHTML: {
                        __html: props.details.answer
                    }
                }
            )
        }
    </li>
);

export default TestOptions;

In parent component I have the following function.

clickTestOptions = (event) => {
    console.log(event.target);
}

The console sometime give me either one of the following result:

<div class="opt-wrap">Mathematics</div>

or,

<li class="mc-opt-cls"><div class="opt-wrap">Mathematics</div></li>

I need always the li element not the div, What is the solution?

Upvotes: 0

Views: 54

Answers (2)

Jason Goemaat
Jason Goemaat

Reputation: 29194

I think you want event.currentTarget, which always refers to the element the listener is attached to.

Upvotes: 1

Shah Alom
Shah Alom

Reputation: 1055

For now my solution is:

let targetOpt = event.target;
console.log('targetOpt:', targetOpt);

if (!targetOpt.classList.contains("mc-opt-cls")) {
    targetOpt = findParentWithClass(event.target, 'mc-opt-cls');
}

console.log('targetOpt:', targetOpt);

findParentWithClass is my helper function:

export const findParentWithClass = (el, cls)=> {
    while ((el = el.parentElement) && !el.classList.contains(cls));
    return el;
};

Upvotes: 0

Related Questions