Event Handlers , State and passing in child Components in React.js

JavascriptMaster
3 min readOct 17, 2022

--

What is event handler ?

Let's use a YouTube example as our guide. When you are clicking on some video cards, you expect this video to play . The same as when you are clicking the SKIP AD button , you expect this will skip the ad . These are the events. An event is an action that takes place when a user interacts with a program. An event handler decides what should happen if an event occurs. I don’t know, but this is the easiest way to explain.

See Console

Now create a new project and try this .

We have created a button , and handleClick is the event handler for the event of onClick. And now when you click this button, a log will be printed every time.

These are the some events we will use in the future readings -

Mouse Events -

onClick , onMouseDown, onMouseEnter, onMouseLeave, onMouseMove, onMouseOut, onMouseOver, and onMouseUp

Keyboard events-

onKeyDown, onKeyPress, onKeyUp

Form events -

onChange , onSubmit

What is state ?

Again, we have to take the example of youtube.com .Every time we click on some card to play the video, this event will play the video. So think about the pseudo-function.

handlePlay(){
Play()
}
button-onClick(handlePlay) - Video

You have clicked the play button, and the button will try to play a video , but we have not given any video . So the play event will not occur. This is just an example . So try to include video in the pseudofunction.

handlPLay(video)
{
video.play()
}
button-onClick(handlPlay(video))- Video

Change the App.js file with this file

And you have learnt to pass the arguments to the event handler . So maybe you are thinking that we can pass some arguments and also change the outcome according to events.

So can we try to build a 101 app? So there will be 3 buttons that will change the argument value to value-1 , 0 and value+1.

Now we have defined one event for each of the event handlers . Try running this code. This will not change the number on the outside, and our code is now purposeless .

This is the primary reason for the existence of state in react.js. You have also read about props. But the props are used to pass data from one component to another. The state is fully private and controlled by the components.

Okay, now change your app. js

That will work. You pass the initial state of the number to the function, and it returns a variable with the updated state value . That’s we have written event handler like this -

onClick={() => handleMinus(number)}

Please try to explore this . If any problem occurred , comment and will try to resolve .

--

--

JavascriptMaster
JavascriptMaster

Written by JavascriptMaster

Hi, I'm a software engineer with a passion for writing about programming languages, particularly Python and JavaScript.