Codecademy Forums

Why don't we set the event listener attribute value to a function call?

Question

Why don’t we set the event listener attribute value to a function call?

Answer

If we set the event listener attribute value to a function call, the function will get called automatically on the page load (when our JSX element renders to the browser) instead of listening for the event and then calling the function.

For example:

import React from 'react';
import ReactDOM from 'react-dom';

function switchHeading() {
  console.log('switchHeading was called!'); 
}

const heading = (
  <h1 onClick={switchHeading}>Click Me!</h1> // onClick will listen for the click event, then will call switchHeading. When that occurrs we will see 'switchHeading was called!' logged to the console
  // if <h1 onClick={switchHeading()}>Click Me!</h1> is used instead, and we set onClick to a function call, we will see 'switchHeading was called!' logged to the console immediately when our JSX renders and not on the click event
)

ReactDOM.render(heading, document.getElementById('app'));
8 Likes