DEV Community

amdiamond107
amdiamond107

Posted on

Event Listeners in JavaScript React

Over the last 15 weeks I've taken a deep dive into frontend and backend software development within The Flatiron School's Software Engineering program. The program is split into five phases, each three weeks long in length, starting with JavaScript, followed by JavaScript React, Python, Python Flask, and a final project putting all of these languages together in a culminating fashion.

My biggest challenge throughout the final project in phase 5 has been re-entering the front end development space after focusing most, if not all, of my attention towards grasping the backend development space (in Python Flask) the past six weeks of the program.

My biggest stumbling block of all was the implementation of event listeners within my new website/app project using JavaScript React, but I think I've got the hang of it again, and I'm focusing this post on that topic, in part, to reinforce that notion for myself...

First and foremost, there was the challenge of parsing out the way this is done in vanilla JavaScript (which I learned in Phase 1) vs. JavaScript React.

Handling events with React elements is very similar to handling events on DOM elements, but there are differences in the syntax...

  • React events are named using camelCase, rather than lowercase.
  • With JSX you pass a function as the event handler, rather than a string.

For example, the HTML:

Image description

whereas, the React version of this would look like:

Image description

Another difference is you can't return false to enforce a prevent default function in React. You must call preventDefault explicitly. For example, with plain HTML, to prevent the default form of submitting, you can write:

Image description

In React, this could instead be:

Image description

It also took me a minute to recall that you can't really implement a website-redirect function within the body of code within an event listener; not without installing some re-routing dependencies in the visual code app at least.

The three common events I focused on re-learning and applying to my project were...

onClick: Occurs when the user clicks on an HTML element, and calls back a function to carry out a desired action, as exemplified in the image below...

Image description

onChange: An attribute used for handling changes to input values, and is often used with , and inputs. Essentially anywhere you need to capture a user's input, this event listener is the one to use, and below is an example...

Image description

onSubmit: The go-to event listener when working with

elements, the submit event interacts with all the data from the form after it gets submitted, at which point you must call event.preventDefault() to prevent the form from automatically making a network request. See example below

Image description

_Resources:
_

Top comments (0)