#7 Handing events in React - Delightful React

Subscribe to my newsletter and never miss my upcoming articles

Before we start doing more with our React components, let's spend a bit more time on theory. Let's understand how we can interact with React elements.

Asset_11.png

*Note: This article is a part of the Delightful React Series, as part of which, I am releasing one chapter every day for 25 days. Please support me in anyway you can! *


Just like HTML elements like buttons can be clicked, inputs can be typed into, etc, React elements can also be interacted with.

  • HTML elements can be given appropriate event listeners like on-click, on-focus etc to respond to user events and take necessary actions.
  • Similarly, React elements can also be given event listeners, like onClick, onFocus, onBlur, onMouseOver etc. which will then be converted to HTML event listeners eventually.
  • The format in which the event listeners are configured in HTML and JSX are different. In HTML, the event listener attribute is a stringified set of instructions. In JSX we can simply use a function .

Events_in_React_Copy.png

  • Another difference is also that in HTML, the event listener names are typically lowercase. In React they are in camel case like the other built-in prop names.

DOM_Events_with_attributes_Copy.png

Synthetic Event

Also, React uses its own event object system called SyntheticEvent. And all event handlers are called with a SyntheticEvent as first argument and it contains useful information about the event that just occurred.

v_copy_4.png So SyntheticEvent is a wrapper on top of the underlying browser event.

  • Common native event utilities that we use often like event.stopPropagation(), event.preventDefault(), event.target are all available on synthetic event as well.

  • In most scenarios we don't need much more than that. But if we want to grab the native event itself from the SyntheticEvent for a very specific high level scenario, we can do so using syntheticEvent.nativeEvent.

DOM_Events_with_attributes_Copy_2.png

  • React needs to figure out which DOM element was eventually rendered from the React element and it needs to coordinate the event listener and the underlying DOM event click.
  • For that reason and more, React uses an event object called SyntheticEvent. We don't have to worry too much about the implementation details of SyntheticEvent. All we need to know is that the synthetic event has a structure that is very similar to native events which makes it very easy to use.

The onClick prop

So now let's try out an example in our code. Let's use the onClick prop on a button that we already created in pages/blogpost.js and add an event listener like so.

<button onClick={(event) => {
    alert("This button was clicked!!")
}} />
    Upvote Post
</button>

So, within the onClick prop, we can pass a function.

  • And within that, we can interact with either the other DOM elements in the page or the browser APIs like alerts, console.log etc. We used an alert here. And this alert will get fired when the button is clicked.
  • A much nicer example to show would be to implement a small counter. And a button can increment that counter's value on click. Stay tuned for this in 2-3 chapters from now.

Events allow users to interact with elements and components

We can also interact with the browser storage just like localStorage, sessionStorage, indexedDB or cookies etc. We will eventually do an example with localStorage in a later chapter, with an onClick event handler on a button.

For now, let's leave it as so.

Let us try another event handler called onMouseOver.

<p onMouseOver={(event) => {
    console.log("hover in");
}} />
    Hover over me
</p>

There are also some events like focus and blur which are handy on input elements. And we can target those events like here.

<input 
    className="border border-black"
    onFocus={() => console.log("input is focused")}
    onBlur={() => console.log("input is blurred")}
/>

Various events can be handled in React

There are various kinds of events that can be handled in react. And you can take a look at all the list of events that react elements can handle in the link over here . Try out various elements and different events on them to get used to event handling in React.

Thanks for following my blogposts so far

We learnt small but important things today. We learnt how we can respond to events on React elements and how we can use them to perform small actions.

Let’s keep moving forward!

Please support my work

Writing blog posts and making videos is an effort that takes many hours in my day. I do it because I love teaching and make great content. However, I need your support too. Please support my work and follow my social accounts to help me continue to make great content. Here are my social links.

Follow me on Twiter

Subscribe to my channel on Youtube

Thank you!

No Comments Yet