×
☰ See All Chapters

Events in ReactJS Elements

In JSX JavaScript code is coupled with your markup, you can quickly add the events while keeping your code well-organized. JSX uses slightly different camelCased names for element.

function FirstComponent() {

  return (

    <button id="myID" onClick={event => alert(event.target.id)} >Click Here</button>

  )

}

export default FirstComponent;

events-in-reactjs-elements-0
 

Since this is JSX, you camelCased onclick, which means you added it as onClick . This onClick attribute uses an anonymous function to retrieve information about the item that was clicked. Same in HTML can be written as below:

<!DOCTYPE html>

<html>

 

<script>

        function test(event) {

                alert(event.target.id);

        }

</script>

 

<body>

        <button id="myID" onclick="test();">Click Here</button>

</body>

 

</html>

Instead of using anonymous function you can declare it outside the main component function. In other words, the function does not need to access the scope of the component. The advantage to keeping them separate is that your component function is slightly shorter and you could move the function out to a separate file later if you wanted to. React event handlers are written inside curly braces. onClick={displayIdOfElemennt} instead of onclick="displayIdOfElemennt"

function FirstComponent() {

  const displayIdOfElemennt = event => alert(event.target.id);

  return (

    <button id="myID" onClick={displayIdOfElemennt} >Click Here</button>

  )

}

 

export default FirstComponent;

Passing Arguments to event handlers

To pass an argument to an event handler, use an arrow function.

function HelloComponent() {

  const testOnclickEvent = (message, event) => {alert(event.target.id); alert(message);}

  return (

    <button id="myID" onClick={(event) => testOnclickEvent("HelloWorld", event)} >Click Here</button>

  )

}

 

export default HelloComponent;

Event handlers have access to the React event that triggered the function. Passing the event argument is not needed when we have no parameters in function. But when there are parameters set in the function and event argument also to be used in function then event argument should be a parameter in function.

 


All Chapters
Author