0

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 ?

2
  • It's a completely different thing in react. Commented Jul 16, 2021 at 9:25
  • 1
    React is opposite. Using addEventListener is bad practice in React. Let React handle events. Use the onClick property. Otherwise React may not know about the event. Note that the onClick in React is not the same as DOM onclick. It is a synthetic event. React will handle it internally or dispatch it to the DOM as appropriate Commented Jul 16, 2021 at 9:25

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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;

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.