Thursday, July 04, 2024

How to Use JSX for Powerful Rendering in React Projects, Example Book List

In the previous lesson of our React tutorial, watch it here; we covered the necessary installations and everything you need to start creating some interesting React components. You learned what React and React Native are. You created your first "Hello World" JSX application. During this process, you might have noticed how React shares many similarities with our Node.js tutorial, watch it here. In this lesson, we will explain what JSX is, what JSX rendering is, expand on the previous lesson with some details we didn't want to overwhelm you with, and help you code a simple component that demonstrates how to add a list of books to an HTML page. This lesson will definitely clarify and simplify the creation of your future React projects. If you asked developers what JSX is, you would probably get at least three different answers.

  • JSX - JavaScript Syntax eXtension, informally JavaScript XML, is a JavaScript extension that allows creating a DOM - Document Object Model tree using syntax similar to XML.
  • JSX is an XML/HTML-like syntax embedded in JavaScript code used to declare React components. It is a language used to describe the UI - User Interface created with React.
  • JSX - JavaScript XML is an extension of the JavaScript programming language that allows HTML-like code within JavaScript.

All three answers are correct even though they define JSX in a total of three different ways.

The developer uses the JSX rendering of the react project

The developer uses the JSX rendering of the react project

Pay attention and see the difference between JSX and JavaScript:

JavaScript:

const element = React.createElement('h1', null, 'Hello, world!');

JSX:

const element <h1> Hello, world! </h1>;

The simplicity of JSX is evident. But what is JSX rendering? JSX rendering is the process of converting JSX code into JavaScript objects that can then be interpreted and displayed in a web browser. When a React application runs, JSX is translated into React.createElement calls that create a virtual DOM - Document Object Model. The virtual DOM is an internal representation of the user interface structure in React. When the application's state changes, React compares the virtual DOM to the real DOM and updates only the parts that have changed, improving the application's performance. In short, JSX makes writing the user interface in React easier, while JSX rendering allows React to efficiently manage updates and maintain a fast and responsive user experience. To avoid getting lost in general theory, it's simpler to understand this entire concept through a practical example.

A Simple Way to Create a Book List Component in React

Assume you have a task to display a list of books on a web page, with the ability to add books to the list, specifically the book titles and authors. Of course, our React component is for demonstration purposes only, and the moment you refresh the web page, the books you added to your list will be automatically removed. In practice, you would probably need to add code to this component to save the book list in a text file or a database. You might also want the ability to delete a book from the list, make changes in case you entered the book details incorrectly, perhaps create data validation to avoid duplicates, or even add Bootstrap to your HTML controls, etc. For this reason, our React component is the most basic, but you can expand it to suit your needs.

If you're wondering why not just do all this in PHP, and why you need React; you should consider an important fact. Unlike PHP, a React component only affects a part of the HTML page and shows you the results without needing to refresh the web page. Imagine if your Facebook page refreshed every time, you clicked a like. That would be a nightmare! So, let's recall how we created our first "Hello World" application in the previous lesson, watch it here; now create a completely new folder in our directory called react_tutorial and name it lesson2. From this directory, start Visual Studio Code with the following command:

manuel@manuel-virtual-machine:~/react_tutorial/lesson2$ code .

Open the Terminal Panel in Visual Studio Code. Type the following command.

manuel@manuel-virtual-machine:~/react_tutorial/lesson2$ npx create-react-app booklist

It took us about 6 minutes, so wait for that time for everything to install. When everything is installed, see in the Explorer Panel what everything has been created for you.

Folder and file structure in React project created to get you started

Folder and file structure in React project created to get you started

The command you previously executed generates the basic project structure for you, which includes the following folders and files:

  • node_modules – This folder contains all external libraries and packages required for your React project. These packages are installed via npm (Node Package Manager) when you run the create-react-app command.
  • public – This folder contains the static resources of your application, such as the index.html file, icons, and other files that are used as part of your user interface.
  • index.html – This is the main HTML file of your application. It defines the basic framework of your web page and includes the necessary JavaScript files.
  • favicon.ico – The icon displayed at the top of the browser tab.
  • src – This folder contains the source code of your React application.
  • index.js – The main JavaScript file used to launch your React application. Here, the necessary components are usually imported, and the main App component is rendered into the HTML DOM - Document Object Model.
  • App.js – The main component of your React application. Here you define the structure of the user interface and the application logic.
  • App.css – The CSS file containing styles for the App.js component.
  • logo.svg – This file contains the React logo, often used in initial projects.
  • serviceWorker.js – This file contains the implementation of the service worker to enable PWA -Progressive Web App capabilities.
  • package.json – The primary file that contains information about your project and the dependencies it uses. It also includes scripts for running, building, and testing your application.
  • README.md – The basic file containing information about your project, including installation instructions, usage, and other useful details.
  • etc.

This organized structure of folders and files will definitely boost your creativity and make working with React projects easier. Create a new folder in the src folder, name it components, and in that folder, create a new file named BookList.jsx. Note that the file name usually starts with a capital letter in practice. In the BookList.jsx file, type the following JavaScript code. 

import React, { useState } from 'react';

function BookList() {

  // Define state for storing books and input values

  const [bookssetBooks] = useState([

    { id: 1title: "The Road to learn React"author: "Robin Wieruch" },

    { id: 2title: "Beginning React"author: "Greg Lim" },

    { id: 3title: "React Explained"author: "Zac Gordon" }

  ]);

  const [newBookTitlesetNewBookTitle] = useState("");

  const [newBookAuthorsetNewBookAuthor] = useState("");

 

  // Function to add a new book

  const addBook = () => {

    const newBook = {

      id: Math.random(),

      title: newBookTitle,

      author: newBookAuthor

    };

    setBooks([...booksnewBook]);

    // Reset input fields after adding a new book

    setNewBookTitle("");

    setNewBookAuthor("");

  };

  return (

    <div>

      <h1>Book List</h1>

      <div>

        <input

          type="text"

          placeholder="Enter title"

          value={newBookTitle}

          onChange={(e=> setNewBookTitle(e.target.value)}

        />

        <input

          type="text"

          placeholder="Enter author"

          value={newBookAuthor}

          onChange={(e=> setNewBookAuthor(e.target.value)}

        />

        <button onClick={addBook}>Add Book</button>

      </div>

      <ul>

        {books.map(book => (

          <li key={book.id}>

            <h3>{book.title}</h3>

            <p>by {book.author}</p>

          </li>

        ))}

      </ul>

    </div>

  );

}

export default BookList;

Take a closer look at this code. When it comes to HTML syntax, it's all grouped into a single structure of <div> elements as child elements, because React only needs one native element to render. Rendering HTML elements using JSX follows regular HTML element syntax but with a few subtle differences in attribute recognition, uppercase and lowercase. This means that React does not recognize the <Button> element, but must be written in lowercase <button>. The JSX markup dictionary is the basic building blocks of React. With them you can encapsulate HTML, create nested elements, create namespace components, embed JavaScript expressions or map collections to elements as in the previous example books.map which returns a new array. React really offers you an extraordinary number of possibilities, some of which we will use ourselves in our React tutorial. Click on the index.html file in the public folder. Then change the title element. 

<title>Book List</title>

This way you can change the name of your website that appears on the top tab of your browser when it displays your website. In index.html, you can also change the logo that was left in the given example, and put one of your own. Click on the App.js file and change the contents of the file to the following.

import React from 'react';

import BookList from './components/BookList';

function App() {

  return (

    <div className="container">

      <BookList />

    </div>

  );

}

export default App;

Note that for the className, element div; you can call it whatever you want. The App() function simply runs through the newly formed <BookList /> element and executes our component.

Executing the booklist React component on the main react project website

Executing the booklist React component on the main react project website

Start the server with the following command.

manuel@manuel-virtual-machine:~/react_tutorial/lesson2/booklist$ npm start

Add a couple of books to your list, you will get a similar result as in the previous picture. If you refresh your web browser, the books you entered will be deleted for reasons we have already explained in this lesson. You can see how creating a Book List example looks like in the video.


React - 2. Rendering with JSX - Book List










No comments:

Post a Comment