3

How do I get the target of the onClick event div.id inside the function showChildren?

Desired result:

div.id

Actual result:

<react></react>

Relevant Razor

  iterateNavigationObject: function(item) {

    var titleStyle = {
      'backgroundColor': 'grey'
    };

    return (
      <div>
        <ul>
          <li style={titleStyle}>
            <div id="asdf" onClick={this.showChildren}>{item.text}</div>//I want the id of this element
              <ul>
                {item.items.map(this.iterateNavigationSubitems, this)}
              </ul>
          </li>
        </ul>
      </div>
    );
  },

  showChildren: function(){
    console.log(event.type);//OUTPUT:  'react-click'
    console.log(event.target);//OUTPUT:  <react></react>
  },

1 Answer 1

3

Change your click handler signature

showChildren: function(event) {
  console.log(event.type);//OUTPUT:  'react-click'
  console.log(event.target);//OUTPUT:  <react></react>
},

Explanation:
you might expect this to work from vanilla JS. Internet Explorer provides a global object window.event, which references the last event. And before IE9 there are no arguments in the handler. This applies to IE only (maybe other browsers as well). React uses it's own synthetic events, thus don't expect this to work. React passes event as first argument to all event listeners.

Regardless, you should not rely on this in React, nor vanilla JS. Always accept event as function argument.

Edit
To pass ID, use higher order function, which returns actual event listener. Update call to this

<div onClick={this.showChildren("asdf")}>{item.text}</div>

Then, update listener to accept ID. You can disregard previous answer in this solution.

showChildren(id) {
  return () => {
    console.log(id);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.