Destructuring And Event Handler In React

Introduction

In the previous article, we learned about the state and its usage, as well as 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 users to extract multiple pieces of data from an array or object and assign them to their own variable. This concept allows us to extract data out of an array or object easily and makes your code readable and usable.

For example, you have an employee with multiple properties.

const employee = {
    name: "emp",
    salary: "10k",
    designation: "tester"
}

Before ES6, you need to access properties as below.

console.log(employee.name);
console.log(employee.salary);
console.log(employee.designation);

Destructuring lets us distribute this code.

const { name, salary, designation } = employee;

The above code is the same as the code shown below.

const name = employee.name;
const salary = employee.salary;
const designation = employee.designation;

Now, the above properties can be accessed without using the employee. prefix.

console.log(name);
console.log(salary);
console.log(designation);

Destructuring props and states

Now, look at the example below. I want to pass by properties in the below-mentioned way.

const personalInfo = {
    name: "xyz",
    address: "150 Seattle",
    zipcode: "111111",
    city: "wc",
    contactNumber: "999999999"
};

const professionalInfo = {
    occupation: "business",
    designation: "CEO",
    salary: "50k"
};

Now, add the above properties in the Employee component in App.js.

import React, { Component } from "react";
import "./App.css";
import logo from "./logo.svg";
import Employee from "./Components/Employee";

class App extends Component {
    render() {
        const personalinfo = {
            name: "xyz",
            address: "150 Seattle",
            zipcode: "111111",
            city: "wc",
            contactnumber: "999999999"
        };
        const proffessionalinfo = {
            occupation: "business",
            designation: "CEO",
            salary: "50k"
        };

        return (
            <p className="App">
                <img src={logo} className="App-logo" alt="logo" />
                <Employee personalinfo={personalinfo} proffessionalinfo={proffessionalinfo}>
                </Employee>
            </p>
        );
    }
}

export default App;

Access the above properties in the Employee component, as below.

import React from 'react';

const Employee = (props) => {

  return (
    <p>
      <legend>Personal Details</legend><br/>
      Name: {props.personalinfo.name}<br/>
      Address: {props.personalinfo.address}<br/>
      Zipcode: {props.personalinfo.zipcode}<br/>
      City: {props.personalinfo.city}<br/>
      Contact Number: {props.personalinfo.contactnumber}<br/>

      <legend>Professional Detail</legend><br/>
      Occupation: {props.professionalinfo.occupation}<br/>
      Designation: {props.professionalinfo.designation}<br/>
      Salary: {props.professionalinfo.salary}<br/>
    </p>
  );
}

export default Employee;

The output will be displayed as below.

 Displayed

In the above code, we need to specify props. personal info or props. professional info for every property.

Now, if we destructure props, we made the changes below in the employee component.

import React from 'react';

const Employee = ({ personalinfo, proffessionalinfo }) => {
  return (
    <p>
      <legend>Personal Details</legend><br/>
      Name: {personalinfo.name}<br/>
      Address: {personalinfo.address}<br/>
      Zipcode: {personalinfo.zipcode}<br/>
      City: {personalinfo.city}<br/>
      Contact Number: {personalinfo.contactnumber}<br/>

      <legend>Professional Detail</legend><br/>
      Occupation: {proffessionalinfo.occupation}<br/>
      Designation: {proffessionalinfo.designation}<br/>
      Salary: {proffessionalinfo.salary}<br/>
    </p>
  );
}

export default Employee;

The important changes are done in the first line. Instead of props, we have passed personal information and professional information objects.

Now, we will be reviewing the output.

Output

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.

<button onclick="showName()">Display Name</button>

While in React, we define this as.

<button onClick={showName}> Display Name </button>

The other difference between them is the value returned by the function.

In HTML normally we write.

<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:

function DisplayLink() {
    function linkClicked(e) {
        e.preventDefault(e);
        console.log("Link Clicked");
    }

    return (
        <a href="#" onClick={linkClicked}> Click me </a>
    );
}

Here, e refers to Synthetic events. 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 passes 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() events. This concept is pooled which means that the SyntheticEvent object will be reused and all properties inside this event become 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, which 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 the destructuring of props and states 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.

Next in this series: Binding Event Handler and Method as Props