Lesson 15 of 16
In Progress

Working with Libraries and Frameworks (jQuery, React, etc.)

As you continue to develop web applications with JavaScript, you may find that you need to use libraries and frameworks to help streamline your development process and add advanced features to your apps. In this chapter, we’ll explore some of the most popular libraries and frameworks for JavaScript, including jQuery, React, and Angular.

What are Libraries and Frameworks?

A library is a collection of pre-written code that provides utility functions and other helpful tools for a specific purpose. A framework is a more comprehensive structure that provides a set of conventions and guidelines for building applications. Both libraries and frameworks can be used to save time and effort when developing applications, but they differ in the level of abstraction and the amount of control they provide.

jQuery

jQuery is a popular library that provides a set of utility functions and methods for interacting with the DOM, making HTTP requests, and animating elements. One of the main benefits of jQuery is that it simplifies common JavaScript tasks and allows you to write shorter, more concise code.

To use jQuery, you’ll need to include the jQuery library in your HTML file. You can either download the library and include it locally, or you can include it from a CDN (Content Delivery Network) by adding a script tag to your HTML file.

<script 
src="https://code.jquery.com/jquery-3.6.0.min.js">
</script>

Once the library is included, you can start using jQuery by selecting elements from the DOM and applying functions and methods to them. For example, to select all the p elements on a page and hide them, you can use the hide function:

$("p").hide();

jQuery also provides a set of events that you can use to respond to user actions such as clicks, hovers, and form submissions. For example, to attach a click event to a button, you can use the click function:

$("button").click(function() {
  // code to execute when the button is clicked
});

React

React is a JavaScript library for building user interfaces. It was developed by Facebook and is now maintained by a community of developers. React allows you to create reusable components that can be easily combined to build complex applications.

One of the main benefits of React is that it uses a virtual DOM (Document Object Model) to optimize updates to the actual DOM. This means that when the state of a component changes, React will only update the parts of the DOM that are necessary, rather than rebuilding the entire DOM tree. This can greatly improve the performance of your application, especially when working with large datasets or frequently changing data.

To use React, you’ll need to include the React library in your HTML file and set up a build process to compile your code. There are several ways to do this, but one popular method is to use the create-react-app tool, which sets up a development environment with a configuration that includes Webpack, Babel, and other tools.

Once you have React set up, you can start creating components. A component is a piece of code that represents a part of a user interface. You can define a component using a JavaScript class or function, and you can use JSX (JavaScript XML) syntax to define the HTML-like structure of the component.

Here’s an example of a component that displays a list of items:

import React from "react";

class List extends React.Component {
  render() {
    return (
      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
      </ul>
    );
  }
}

To use the component, you can include it in your HTML file like this:

<div id="root"></div>

And you can render the component to the root element using the ReactDOM.render method:

import React from "react";
import ReactDOM from "react-dom";
import List from "./List";

ReactDOM.render(<List />, document.getElementById("root"));

React components can also have state and props (properties). State is a way to manage data that can change within a component, and props are a way to pass data from a parent component to a child component.

For example, here’s a component that has a stateful value and a prop that controls the color of the text:

import React from "react";

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p style={{ color: this.props.color }}>
          The count is {this.state.count}.
        </p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}

To use the component, you can pass a value for the color prop like this:

ReactDOM.render(
  <Counter color="#00b8d4" />,
  document.getElementById("root")
);

Angular

Angular is a full-featured framework for building single-page applications. It provides a set of conventions and tools for creating complex applications with a modular architecture.

Angular uses a component-based architecture, similar to React, but it also provides additional features such as dependency injection, routing, and a built-in HTTP client. It also has a templating syntax called HTML templates, which allows you to define the structure of your components using HTML-like syntax.

To use Angular, you’ll need to include the Angular library in your HTML file and set up a build process to compile your code. You can use the Angular CLI (Command Line Interface) tool to set up a development environment and create a new Angular project.

Once you have Angular set up, you can start creating components. A component in Angular is a class that defines the properties and behavior of a view element. You can use the @Component decorator to define the component, and you can use the template or templateUrl property to define the HTML template for the component.

Here’s an example of a simple component that displays a greeting:

import { Component } from "@angular/core";

@Component({
  selector: "app-greeting",
  template: `
    <h1>Hello, World!</h1>
  `
})
export class GreetingComponent {
  // component logic goes here
}

To use the component, you can include it in your HTML file like this:

<app-greeting></app-greeting>

Angular components can also have inputs and outputs, which allow you to pass data between components. For example, here’s a component that has an input for a user name and an output that fires an event when the user clicks a button:

import { Component, Input, Output, EventEmitter } from "@angular/core";

@Component({
  selector: "app-user",
  template: `
    <p>{{ userName }}</p>
    <button (click)="onClick()">Click me</button>
  `
})
export class UserComponent {
  @Input() userName: string;
  @Output() clicked = new EventEmitter<void>();

  onClick() {
    this.clicked.emit();
  }
}

To use the component, you can bind to the userName input and listen to the clicked output like this:

<app-user [userName]="'John'" (clicked)="handleClick()"></app-user>

Angular also provides a powerful routing system that allows you to define multiple routes for your application and navigate between them. You can define routes using the RouterModule and the Routes array.

For example, here’s how you can define two routes for an application:

import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";

import { HomeComponent } from "./home.component";
import { AboutComponent } from "./about.component";

const routes: Routes = [
  { path: "", component: HomeComponent },
  { path: "about", component: AboutComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

You can then use the routerLink directive to create links to the different routes, and you can use the router-outlet directive to define where the content for the current route will be displayed.

<nav>
  <a routerLink="/">Home</a>
  <a routerLink="/about">About</a>
</nav>

<router-outlet></router-outlet>

Conclusion

Libraries and frameworks can greatly improve your productivity when developing applications with JavaScript. They provide a set of tools and conventions that can help you write cleaner, more maintainable code and build more complex applications faster. In this chapter, we’ve explored some of the most popular libraries and frameworks, including jQuery, React, and Angular. Whether you choose to use a library or a framework will depend on your specific needs and preferences, but either way, you’ll be able to take advantage of the powerful capabilities that these tools provide.

Exercises

To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.

Write a jQuery function that selects all the p elements on a page and toggles their visibility when a button is clicked.

$(document).ready(function() {
  $("button").click(function() {
    $("p").toggle();
  });
});

Write a React component that displays a form with two input fields (email and password) and a submit button. When the form is submitted, display an alert with the values of the input fields.

import React from "react";

class Form extends React.Component {
  handleSubmit(event) {
    event.preventDefault();
    const email = event.target.elements.email.value;
    const password = event.target.elements.password.value;
    alert(`Email: ${email} Password: ${password}`);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Email:
          <input type="email" name="email" />
        </label>
        <br />
        <label>
          Password:
          <input type="password" name="password" />
        </label>
        <br />
        <button type="submit">Submit</button>
      </form>
    );
  }
}

Write an Angular component that displays a list of users, each with a name and an avatar. The component should have an input for a list of users and an output that fires an event when a user is clicked.

import { Component, Input, Output, EventEmitter } from "@angular/core";

@Component({
  selector: "app-user-list",
  template: `
    <ul>
      <li *ngFor="let user of users" (click)="handleClick(user)">
        {{ user.name }}
        <img [src]="user.avatarUrl" [alt]="user.name" />
      </li>
    </ul>
  `
})
export class UserListComponent {
  @Input() users: any[];
  @Output() userClicked = new EventEmitter<any>();

  handleClick(user) {
    this.userClicked.emit(user);
  }
}

Write a jQuery function that makes an AJAX request to a REST API and displays the result in a table.

$(document).ready(function() {
  $.ajax({
    url: "https://api.example.com/users",
    success: function(result) {
      const table = $("<table></table>");
      result.forEach(function(user) {
        const row = $("<tr></tr>");
        row.append(`<td>${user.name}</td>`);
        row.append(`<td>${user.email}</td>`);
        table.append(row);
      });
      $("#result").append(table);
    }
  });
});

Write a React component that uses the useEffect hook to fetch data from a REST API and display it in a list.

import React, { useEffect, useState } from "react";

function UserList() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch("https://api.example.com/users")
      .then(response => response.json())
      .then(result => setUsers(result));
  }, []);

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}