Saturday, March 6, 2021

Displaying List in React

Lists are very useful when it comes to developing the UI of any website. Lists are mainly used for displaying menus in a website, for example, the navbar menu. In regular JavaScript, we can use arrays for creating lists. We can create lists in React in a similar manner as we do in regular JavaScript. We will see how to do this in detail further in this article.

Using JSX we can show lists using JavaScript's built-in Array.map() method. The .map() method is often used to take one piece of data and convert it to another. In our scenarios, we are taking data and converting it to a piece of our view.

A Simple Example

Let's say we have a list of array that we want to show in a list:

 

import React from "react";

export default function ArrayMap() {

  const arr = [1020304050];

  const newArr = arr.map(function (num) {

    console.log("Num"num);

    return <li>{num * 2}</li>;

  });

  console.log("Old Array"arr);

  console.log("New Array"newArr);

  return <ul>{newArr}</ul>;
}

  

This component uses Array’s built-in map function to create a new array newArr that has the same number of elements, and where each element is the result of calling the function you provide. The {} brackets are used to render the array of elements.

import React from "react";

export default function ArrayMap() {

  const arr = [1020304050];

  return (

    <ul>
      { 
arr.map((num=> {

        return <li>{num}</li>;
      })}

    </ul>

  );
} 

 

The above is the shorthand code for write the map function. Since we are not doing anything in the function's block body, we can also refactor it to a concise body and omit the return statement and the curly braces for the function body:

return (
  <ul>

    {arr.map(num =><li>{num}</li>)}

  </ul>
);


Rendering lists inside Components

So from the component’s point of view, we have to pass a list to a component using props and then use this component to render the list to the DOM. We can update the above code in which we have directly rendered the list to now a component that will accept an array as props and returns an unordered list. 

 

const mylist = [1020304050];

const App = () => <ListComponent list={mylist} />;

const ListComponent = ({ list }) => (

  <ul>

    {list.map((item=> (

      <li>{item}</li>

    ))}

  </ul>
);
export default App;

You can see in the above output that the unordered list is successfully rendered to the browser but a warning message is logged to the console.  

Warning: Each child in an array or iterator

         should have a unique "key" prop 

The above warning message says that each of the list items in our unordered list should have a unique key. A “key” is a special string attribute you need to include when creating lists of elements in React. We will discuss about keys in detail in further articles. For now, let’s just assign a key to each of our list items in the above code.

Below is the example where we display the list of Objects with keys.  

 

Display Object List in React

Displaying items from a list of objects in React is very simple. We can iterate over a list of objects using the .map() method in React JSX. Here is the example in which we mapped a list of objects and displayed them in the React app.

 

import React, { useState } from "react";


import "../node_modules/bootstrap/dist/css/bootstrap.css";

export default function DemoMap() {

  const [useraddUser] = useState([
    {
      id: 1,
      username: "pankkap",
      password: "pankaj123",
    },
    {
      id: 2,
      username: "manishkumar",
      password: "manish456",
    },
    {
      id: 3,
      username: "sachinyadav",
      password: "sachin789",
    },
  ]);

  const renderUser = (userindex=> {
    return (

      <tr key={index}>

        <td>{user.id}</td>

        <td>{user.username}</td>

        <td>{user.password}</td>

      </tr>
    );
  };
  return (

    <div className="container mt-3">

      <table class="table">

        <thead class="thead-light">

          <tr>

            <th>#</th>

            <th>User name</th>

            <th>Password</th>

          </tr>

        </thead>

        <tbody>{user.map(renderUser)}</tbody>

      </table>

    </div>
  );
}

Output:

The key attribute is necessary for React to identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. Since React uses a virtual DOM and depends on the key to identifying items of a list, so in the above list example, we provided a unique id to every list item.


Sunday, February 28, 2021

React Events

In web development, events represent actions that happen in the web browser. By responding to events with event handlers, you can create dynamic JavaScript applications that respond to any user action, including clicking with a mouse, scrolling along a webpage, touching a touch screen, and more.

In React apps, you can use event handlers to update state data, trigger prop changes, or prevent default browser actions. React has its own event handling system which is very similar to handling events on DOM elements. The react event handling system is known as Synthetic Events. SyntheticEvent closely emulates the standard browser event, but provides more consistent behavior for different web browsers. 

Handling events with react have some syntactic differences from handling events on DOM. These are:

  1. React events are named as camelCase instead of lowercase.
  2. With JSX, a function is passed as the event handler instead of a string. For example:

Event declaration in plain HTML:

<button onclick="showMessage()">

       Hello JavaTpoint

</button>

Event declaration in React:

<button onClick={showMessage}>

      Hello JavaTpoint

</button>

3. In react, we cannot return false to prevent the default behavior. We must call preventDefault event explicitly to prevent the default behavior. For example:

In plain HTML, to prevent the default link behavior of opening a new page, we can write:

<a href="#" onclick="console.log('You had clicked a Link.'); return false">

    Click_Me

</a> 

In React, we can write it as:

function ActionLink() {

  function handleClick(e) {

      e.preventDefault();

      console.log('You had clicked a Link.');

  }

  return (

      <a href="#" onClick={handleClick}>

            Click_Me

      </a>

  );

} 

In the above example, e is a Synthetic Event which defines according to the W3C spec.

Now let us see how to use Event in React.


onClick Event handler in React

The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app.

To listen to events in React, add the onClick attribute, which is the event handler, to the target element. This specifies the function to be executed when that element is clicked.

import React, { Component } from "react";
class ShowAlert extends Component {
  showAlert() {
    alert("I'm an alert");
  }
  render() {
    return <button onClick={this.showAlert}>show alert</button>;
  }
}
export default ShowAlert;
Output: 

In the example above, the onClick attribute is set to the showAlert function, which alerts a message. This means that whenever the button is clicked, the showAlert function is called, which, in turn, shows the alert box.

 

Handling events in class components

In JavaScript, class methods are not bound by default. Therefore, it’s necessary to bind functions to the class instance.

Binding in the render() method: One way to resolve the problem of binding is to call bind in a render function. This is done by binding it in the render() function. This method requires calling .bind(this) in the render() function.

<button onClick={this.showAlert.bind(this)}>show alert</button>

 

Binding in the constructor() method: If binding in the render doesn’t work for you, you can bind in the constructor. See an example below:

class ShowAlert extends Component {

  constructor(props) {

    super(props);

    this.showAlert = this.showAlert.bind(this);

  }

The first this.showAlert refers to the showAlert method. Since this is done in the constructor, this refers to the ShowAlert class component.

The second this.showAlert is also referring to the same showAlert() method, but we are now calling .bind() on it.

The final this is the context we are passing to .bind(), and it refers to the ShowAlert class component.

It’s also important to note that if showAlert isn’t bound to the class instance, it won’t be able to access this.setState because this will be undefined. This is another important reason to bind event handling functions.

Binding in the arrow function: You can handle events in class components by binding them with the fat arrow function. ES7 class properties enable bindings at the method definition, as shown in the example below. By definition, an arrow function expression has a shorter syntax than a function expression and does not have its own thisargumentssuper, or new.target.

showAlert=()=> {

    alert("I'm an alert");

  }

 

onChange Event handler in React

In the below example, we have used only one component and adding an onChange event. This event will trigger the changeText function, which returns the company name.

import React, { Component } from "react";
class DemoOnChange extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tutorialName: "",
    };
  }
  changeText(event) {
    this.setState({
      tutorialName: event.target.value,
    });
  }
  render() {
    return (
      <div>
        <h2>onChange Event Example</h2>
        <label htmlFor="name">Enter Tutorial name: </label>
        <input
          type="text"
          id="companyName"
          onChange={this.changeText.bind(this)}
        />
        <h4>You entered: {this.state.tutorialName}</h4>
      </div>
    );
  }
}
export default DemoOnChange;

Output

When you execute the above code, you will get the following output.

After entering the name in the textbox, you will get the output as like below screen.

 

onSubmit Event handler in React

You can control the submit action by adding an event handler in the onSubmit attribute:

Example

import React, { Component } from "react";

class MyForm extends React.Component {

  constructor(props) {

    super(props);

    this.state = { username: "" };

  }

  mySubmitHandler = (event=> {

    event.preventDefault();

    alert("You are submitting " + this.state.username);

  };

  myChangeHandler = (event=> {

    this.setState({ username: event.target.value });

  };

  render() {

    return (

      <form onSubmit={this.mySubmitHandler}>

        <h2>onSubmit Event Example</h2>

        <p>Enter your name, and submit:</p>

        <h1>{this.state.username}</h1>

        <input type="text" onChange={this.myChangeHandler} />

        <input type="submit" />

      </form>

    );

  }

}

export default MyForm;

Note that we use event.preventDefault() to prevent the form from actually being submitted.