Destructuring And Event Handler In React

Introduction

 
In the previous article, we learned about state and its usage, and the difference between props and state. Now, in this article, we will go ahead and review a small concept of destructuring props and states and the basics of event handling in React.js.
 

Destructuring

 
Destructuring is a simple concept introduced in React ES6. It is a JavaScript feature that allows the users to extract multiple pieces of data from an array or object and assign them to their own variable. This concept allows us to easily extract data out of an array or object, and makes your code readable and usable.
 
For example, you have an employee with multiple properties.
  1. const employee = {  
  2.     name : "emp",  
  3.     salary:"10k",  
  4.     designation:"tester"  
  5. }  
Before ES6, you need to access properties as below.
  1. console.log(employee.name);  
  2. console.log(employee.salary);  
  3. console.log(employee.designation);  
Destructuring let us distribute this code.
  1. const {name,salary,designation} = employee 
The above code is same as the code shown below.
  1. const name = employee.name;  
  2. const salary = employee.salary;  
  3. const designation = employee.designation;  
Now, the above properties can be accessed without using the employee. prefix.
  1. console.log(name);  
  2. console.log(salary);  
  3. console.log(designation);  

Destructuring props and states

 
Now, look at the example below. I want to pass by properties in the below-mentioned way.
  1. const personalinfo =  
  2. {  
  3.      name: "xyz",  
  4.      address: "150 seattle",  
  5.      zipcode: "111111",  
  6.      city: "wc",  
  7.      contactnumber: "999999999"  
  8. }  
  9.   
  10. const proffessionalinfo =  
  11. {  
  12.      occupation : "business",  
  13.      designation : "CEO",  
  14.      salary : "50k"  
  15. }  
Now, add the above properties in Employee component in App.js.
  1. import React,{Component} from "react";  
  2. import "./App.css";  
  3. import logo from "./logo.svg";  
  4. import Employee from "./Components/Employee";  
  5.   
  6. class App extends Component {  
  7.          render(){  
  8.                   const personalinfo =  
  9.                   {  
  10.                            name: "xyz",  
  11.                            address: "150 seattle",  
  12.                            zipcode: "111111",  
  13.                            city: "wc",  
  14.                            contactnumber: "999999999"  
  15.                   }  
  16.                   const proffessionalinfo =  
  17.                   {  
  18.                            occupation : "business",  
  19.                            designation : "CEO",  
  20.                            salary : "50k"  
  21.                   }  
  22.   
  23.                   return (  
  24.                            <div className="App">  
  25.                                     <img src={logo} className="App-logo" alt="logo"/>  
  26.                                     <Employee personalinfo={personalinfo} proffessionalinfo={proffessionalinfo} >  
  27.                                     </Employee>  
  28.                            </div>  
  29.                   );  
  30.          }  
  31. }  
  32.   
  33. export default App;  
Access the above properties in Employee component, as below.
  1. import React from 'react';  
  2.   
  3. const Employee = (props) => {  
  4.   
  5. return(  
  6.     <div>  
  7.           <legend>Personal Details</legend><br/>  
  8.           Name : {props.personalinfo.name}<br/>  
  9.           address : {props.personalinfo.address}<br/>  
  10.           zipcode : {props.personalinfo.zipcode}<br/>  
  11.           city : {props.personalinfo.city}<br/>  
  12.           contactnumber : {props.personalinfo.contactnumber}<br/>  
  13.   
  14.           <legend>Proffessional Detail</legend><br/>  
  15.           occupation : {props.proffessionalinfo.occupation}<br/>  
  16.           designation : {props.proffessionalinfo.designation}<br/>  
  17.           salary : {props.proffessionalinfo.salary}<br/>  
  18.    </div>  
  19.   )  
  20. }  
  21.   
  22. export default Employee;  
The output will be displayed as below.
 
Destructuring and Event Handler in React
In the above code, we need to specify props.personalinfo or props.proffessionalinfo for every property.
 
Now, if we destructure props, we made the below changes in Employee component.
  1. import React from 'react';  
  2.   
  3. const Employee = ({personalinfo,proffessionalinfo}) => {  
  4.          return(  
  5.                   <div>  
  6.                         <legend>Personal Details</legend><br/>  
  7.                         Name : {personalinfo.name}<br/>  
  8.                         address : {personalinfo.address}<br/>  
  9.                         zipcode : {personalinfo.zipcode}<br/>  
  10.                         city : {personalinfo.city}<br/>  
  11.                         contactnumber : {personalinfo.contactnumber}<br/>  
  12.   
  13.                         <legend>Proffessional Detail</legend><br/>  
  14.                         occupation : {proffessionalinfo.occupation}<br/>  
  15.                         designation : {proffessionalinfo.designation}<br/>  
  16.                         salary : {proffessionalinfo.salary}<br/>  
  17.                         </div>  
  18.          )  
  19. }  
  20.   
  21. export default Employee;  
The important changes are done in the first line. Instead of props, we have passed personalinfo and proffessionalinfo object.
 
Now, we will be reviewing the output.
 
Destructuring and Event Handler in React
The output remains the same but now the code is more readable and clean.
 
So, this is a way to destructure props and in the same way, we can destructure the state.
 

Event Handling

 
Event handling is the same method we use in JavaSript. It is a handler that determines what actions need to be taken when an event is fired. Here, an event refers to a mouse click, button click, mouse hover, text input, and so on.
 
In React, all event handlers are defined in camel case, i.e., in JavaScript onclick will be defined as onClick() in React application.
Unlike in HTML, in JSX, we pass a function as an event handler rather than a string.
 
For example, in HTML, we used to define the function on button click as below.
  1. <button onclick =”showName()”> Display Name  
  2. </button>  
While in React, we define this as:
  1. <button onclick ={showName}> Display Name  
  2. </button>  
The other difference between is the value returned by function.
 
In HTML normally we write,
  1. <a href=”#” onclick=”console.log(‘Link Clicked’); return false;”>Click me</a>  
While in React, False cannot be returned. We need to compulsorily add it to prevent the default behavior. You need to call preventDefault explicitly. For example -
  1. function DisplayLink(){  
  2.    function linkClicked(e){  
  3.            e.preventDefault(e);  
  4.            console.log(“Link Clicked”);  
  5.     }   
  6.   
  7.     return(  
  8.           <a href=”#” onClick={linkClicked}> Click me </a>   
  9.     );  
  10. }  
Here, e refers to Synthetic event. React implements its own events to provide cross-browser compatibility support. Basically, React defines the browser native event into an instance of React SyntheticEvent and passed it to the React handlers.
 

Synthetic Events

 
Synthetic event is the concept introduced by React to provide cross-browser functionality. It has the same interface as the browser’s native event which includes stopPropagation() and preventDefault() event. This concept is pooled which means that SyntheticEvent object will be reused and all properties inside this event became null after event callback due to performance reasons, as this event cannot be used in an asynchronous way.
 
If required to use SyntheticEvent in an asynchronous way, the event.persist() method is used, that will remove SyntheticEvent() from the pool and allow references to the event to be retained by user code.
 

Conclusion

 
In this article, we learn about destructuring of props and state in React and also about some basic concepts of event handling in React and how it is different from basic HTML. In the next article, we will learn in detail about event handling and rendering the props techniques in React. 
 
Author
Priyanka Jain
0 9.6k 893.6k
Next » Binding Event Handler And Method As Props In React