Handling React Events

Jeff P
1 min readDec 17, 2023

--

It is important to understand that when we use react event handlers, we use callback functions…

For example, if we want to use the “onClick” handler inline to make an alert popup appear on screen, we would NOT do something like this…

        <button
style={{ backgroundColor: "#7950f2", color: "#fff" }}


onClick={alert("WRONG!")}
>
Previous
</button>

If we did this without a callback function, the alert would appear immediately as soon as the page is loaded!

The correct way is to use a callback inline, to ensure the function only gets called when someone clicks on the button…

 <button
style={{ backgroundColor: "#7950f2", color: "#fff" }}

onClick={() => alert("CORRECT!")}
>
Previous
</button>

This is different to when we define the function to call, rather than calling inline.

For example:

function handlePrevious() {
alert("Correct!");
}

<button
style={{ backgroundColor: "#7950f2", color: "#fff" }}

onClick={handlePrevious}
>
Previous
</button>

So when we don’t call a function inline, we just specify the function we want to call.

--

--

Jeff P
Jeff P

Written by Jeff P

I tend to write about anything I find interesting. There’s not much more to it than that really :-)

No responses yet