ReactJS Tutorial – 14 – Binding Event Handlers
- December 24, 2023
- Posted by: MainInstructor
- Category: Go JavaScript React VSCode
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1703386348_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: ReactJS Tutorial – 14 – Binding Event Handlers
In this video let’s learn how to bind event handlers in react components before we begin let me tell you that the reason we bind event handlers in react is purely because of the way this keyword works in JavaScript it is not because of how react works I will give
You a very simple example in the context of react components to help you understand why event binding is required but my recommendation here for you is to go through this keyword and how the value of this keyword is determined in JavaScript this video will make much more sense to you once you’re
Comfortable with the basics of this keyword in JavaScript alright let’s get started what I want to achieve in this video is on the click of a button we simply change a message which is part of the component state so first I am going to create a new file
Called event mind dot J s within the file I will use the react snippet RC e to create a class component I will remove the named export and include the component in the app component for the JSX I will simply add a button that says click
Now if I save the file and take a look at the browser you should be able to see the button click Next let’s create a state property called message and bind it to the user interface so in the component I am going to add a constructor using the snippet R Const
Within the constructor a call to super and a state property called message initialized to hello now in the render method a div tag with the content this dot state dot message if we save the file and take a look at the browser you should be able to see the message
Hello now let’s change this message to goodbye when the user clicks on the button we’re collecting from the last video we add the on click attribute and then we pass in the event handler within curly braces this dot click handler and let’s define the method right after the constructor click
Handler and to change state we need to use the set state method this dot said state and we want to set the message to goodbye if I save this and go back to the browser and click on the button you can see that our application breaks and if
You take a closer look at the error it says cannot read property set state of undefined so let me go back to vs code and comment out the set state method and instead simply log to the console that this keyword now if we go back to
The browser and click on the button you can see that undefined is logged in the console so this keyword within our event handler is undefined and let me tell you this is the typical behavior in JavaScript I won’t go into the details of why it is undefined though that is
JavaScript related and not react specific please do spend a few minutes reading up on this keyword if you want to understand why the value is undefined but what I want you to ultimately keep in mind is this keyword is undefined in an event handler and that is the reason
Event binding is necessary in react class components now there are a number of ways to bind event handlers in react when you go through articles or blog posts or other videos you might find all different variants of binding the event handlers so in this video I will go over all of them
The first option we have is to use the bind keyword and bind the handler in the render method so on click this dot click handler dot bind and we pass in this keyword now let me also uncomment set state let’s save the file and go back to
The browser now when I click on the button you can see that the set state method works without any errors the message now reads goodbye and this keyword as you can see in the console is not undefined anymore it refers to the event bind component instance although this option works perfectly fine every
Update to the state will cause the component to rerender this in turn will generate a brand new event handler on every render although the impact on performance is not severe in small applications it could be troublesome in large applications and components that contain nested children components so approach
One binding in the render method the second approach is to use arrow functions in the render method so let me comment out the first approach and show you the second one the arrow function approach is simply calling the event handler in the arrow function body so on click and within
Curly braces we are going to have an arrow function empty parentheses fat arrow syntax and then the event handler this dot click handler notice that we don’t need curly braces or the return keyword for the arrow function body and that is because the function body is a single statement
Also you can notice that we are calling the event handler and returning that value that is why parentheses is required in this approach if I now save the file and take a look at the browser clear the console and click on the button you can see that the message
Changes from hello to goodbye so the second approach also works as expected but similar to the first approach this also has performance implications in some scenarios if you can recollect this is the approach we use in the previous few videos so second approach is using arrow functions in the
Render method next let’s discuss approach number three and this is the approach you are going to see in most of the cases and it is also the approach in the official react documentation this approach deals with binding the event handler in the constructor as opposed to
Binding in the render method so in the constructor we simply add a line this dot click handler is equal to this dot click handler dot bind and passing the disk keyword and in the render method we can go back to this dot click handler save the file go
Back to the browser here the console and click on the button you should be able to see the message change from hello to goodbye so that is the third approach binding in the class constructor because the binding happens once in the constructor this is better compared to
Binding in the render method so approach number three binding in the constructor the final approach is to use an arrow function as a class property basically change the way you define your method in the class let me comment out the binding in the constructor the existing click
Handler and now define it with the new approach click handler is going to be equal to an arrow function and within the other function this dot set state message set to goodbye if you save the file and take a look at the browser you can see that the message
Changes on button click this keyword has the expected value within the handler method so those are the four approaches binding in render arrow function in render binding in the class constructor and finally class property as arrow functions the first approach is something you might not want to use because of performance implications the
Second approach although is similar to approach number one is probably the easiest way to pass parameters if your code doesn’t involve three rendering nested children components this approach is still a viable option react documentation suggests either approach number three or approach number four as approach number four is still an
Experimental feature approach number three which is binding in the constructor is your best option right now however create react app dust support the class property approach so there is nothing wrong with using approach number four in fact when the class property approach becomes an accepted feature it would probably be
The go-to approach I will try to stick to approach number three or four for most parts in this series and when we need to pass parameters I might resort to approach number two for its simplicity so there you go the four different ways to bind event handlers in react thank you guys for
Watching don’t feel substantial
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
How 2nd method using arrow function in event handler in render() creates issues if it has nested components?
Great presentation. I would recommend a variation on binding in the constructor. Instead bind on method creation in the class.
clickHandler = function(){ … }.bind(this);
This keeps the binding with the function when it is created.
completed video 14. Thank You : -)
Thank you!
you are loosing your American accent some of the places. So better to go with original accent instead of faking it. Otherwise content is good!
Short course but on point.
Won't it be easier to use the previous method use under setState in video 10?
i can do this with usestate
Thank you
It's really great how you give examples for both class based and functional components.
in 2023 ur videos are the best from all other tutors
thanks for the superb tutorial😍
Why bind was not required in video 10 ?
Fake accents are always annoying
This is really very helpfull tutorial
You guys are professional teachers. Awesome..
can anyone pls explain what is 'this' referring to here in 1st method:- <button onClick={this.clickHandler}>Click Me</button>
This course so far is the most intuitive one, I'm loving it !
in the setstate lesson we had a similar situation width a class component but in that case we hadn't the undefined problem can you tell me why ? thanks
when i'm using setstate no error is coming it is simply printing Goodbye