JSXStarter
JSXStarter

Reputation: 51

How can I use event listener in ReactJS?

in tutorials I'm seeing something like that :

import React from 'react';
function App(){ 
  return(
    <div>
    <h1 onClick={functionName}>Hello React</h1>
  </div>
  );

  
}
export default App;

but I think adding "onClick" event to an element is a bad practice , instead we were adding event listener with vanilla JS , but now . I don't know if it is OK or not in reactJS? is there better way or this is what it is ?

Upvotes: 0

Views: 222

Answers (2)

Jibin Thomas
Jibin Thomas

Reputation: 864

This is how to do event handling in React. Also take a look at the official documentation. https://reactjs.org/docs/handling-events.html


import React from 'react';
function App(){ 
  const doSomething = (e) => {
    console.log('event', e)
  }

  return(
    <div>
    <h1 onClick={doSomething}>Hello React</h1>
  </div>
  );

  
}
export default App;

Upvotes: 2

Quentin
Quentin

Reputation: 943157

but I think adding "onClick" event to an element is a bad practice

It isn't. Do not confuse JSX properties with HTML attributes.


Getting a reference to the element and then using addEventListener in React, on the other hand, is a bad practise as it bypasses React's methods for keeping its internal model in sync with the DOM.

Upvotes: 3

Related Questions