Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React event.target is not the element I set event Listener on

const onClick = (e) => {
  console.log(e.target);
}
const App = () => (
  <button
    name={'YES'}
    className="btn waves-effect waves-light left blue darken-4"
    onClick={onClick}
  >
    Yes
    <i className='material-icons left'>done</i>
  </button>
);

ReactDOM.render(<App />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app">

I need e.target to be <button> in all possible cases, but when I click on <i>(or any other element as it seems), the target is <i> respectively. Its probably not error, but i don't know what to do about it.

like image 623
Piliponful Avatar asked Mar 06 '17 19:03

Piliponful


People also ask

How do I add an event listener to a React component?

When using React you should generally not need to call addEventListener to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered. When you define a component using an ES6 class, a common pattern is for an event handler to be a method on the class.

Are react events the same as native events?

React events do not work exactly the same as native events. See the SyntheticEvent reference guide to learn more. When using React, you generally don’t need to call addEventListener to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered.

How do you handle events in react JS?

Handling Events. Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences: React events are named using camelCase, rather than lowercase. With JSX you pass a function as the event handler, rather than a string.

What is the changeevent type in react?

The ChangeEvent type is imported from React and used against the event that is passed from the input element. Let’s look at a complete form and how to add type to the event handler for the input and also the form submission. React provides a FormEvent type you can use and that is passed to the handleSubmit function.


1 Answers

Use event.currentTarget, which will always be the element on which the handler was added. event.target will always be the element on which the event occurred.

<button
  name={answerTypes.YES}
  className="btn waves-effect waves-light left blue darken-4"
  onClick={this.onClick}
>
  Yes
  <i className='material-icons left'>done</i>
</button>

onClick(e) {
  console.log(e.currentTarget);
}
like image 96
Ross Allen Avatar answered Oct 04 '22 20:10

Ross Allen