Where is this function getting its argument from?

Hello!

I’m on this lesson (jsx-event-listeners): here.

The following code is used in the example, and I don’t understand how the makeDoggy function, which takes a parameter e is getting that parameter filled with an argument when it is called within the curly braces. Can someone explain how the function gets the necessary argument to operate correctly? (also why doesn’t it require instantiation with parentheses?)

import React from 'react';
import { createRoot } from 'react-dom/client';

const container = document.getElementById('app');
const root = createRoot(container);
function makeDoggy(e) {
  // Call this extremely useful function on an <img>.
  // The <img> will become a picture of a doggy.
  e.target.setAttribute('src', 'https://content.codecademy.com/courses/React/react_photo-puppy.jpeg');
  e.target.setAttribute('alt', 'doggy');
}

const kitty = (
	<img 
		src="https://content.codecademy.com/courses/React/react_photo-kitty.jpg" 
		alt="kitty"
    onClick={makeDoggy} />
);

root.render(kitty);

On a high-level it’s really about state-management and event-listeners. Listeners update about recent events. An event object might capture a snapshot of the state for that particular event (if it was a click, what were the x,y coordinates of the click, what was the time of the click, was it a right or left click, etc.).

Your browser has event listeners for all sorts of input (which you can check with your browser tools). By adding an event listener, you get a snapshot for whatever subset of events you want to listen for. Some patterns in function calls are implicit for this, as is the case here (as if to say, it’s so common that we’re just going to give it every time).

1 Like