Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

React and React Native - Fifth Edition

Mikhail Sakhniuk
Visit to download the full and correct content document:
https://ebookmass.com/product/react-and-react-native-fifth-edition-mikhail-sakhniuk/
React and React Native
Copyright © 2024 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a


retrieval system, or transmitted in any form or by any means, without the
prior written permission of the publisher, except in the case of brief
quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the
accuracy of the information presented. However, the information contained in
this book is sold without warranty, either express or implied. Neither the
author, nor Packt Publishing, and its dealers and distributors will be held
liable for any damages caused or alleged to be caused directly or indirectly
by this book.

Packt Publishing has endeavored to provide trademark information about all


of the companies and products mentioned in this book by the appropriate use
of capitals. However, Packt Publishing cannot guarantee the accuracy of this
information.

Early Access Publication: React and React Native

Early Access Production Reference: B19636

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK

ISBN: 978-1-80512-730-7
www.packt.com
Table of Contents
1. React and React Native, Fifth Edition: Build cross-platform JavaScript
and TypeScript apps for the web, desktop, and mobile
2. 1 Why React?
I. Before you begin: Join our book community on Discord
II. What is React?
III. React is just the view layer
IV. Simplicity is good
V. Declarative UI structures
VI. Data changes over time
VII. Performance matters
VIII. The right level of abstraction
IX. What's new in React?
X. Setup a new React project
i. Using Web Bundlers
ii. Using Frameworks
iii. Online Code Editors
XI. Summary
3. 2 Rendering with JSX
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Your first JSX content
i. Hello JSX
ii. Declarative UI structures
IV. Rendering HTML
i. Built-in HTML tags
ii. HTML tag conventions
iii. Describing UI structures
V. Creating your own JSX elements
i. Encapsulating HTML
ii. Nested elements
iii. Namespaced components
VI. Using JavaScript expressions
i. Dynamic property values and text
ii. Handling events
iii. Mapping collections to elements
VII. Building fragments of JSX
i. Using wrapper elements
ii. Using fragments
VIII. Summary
4. 3 Understanding React Components and Hooks
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Introduction to React Components
IV. What are component properties?
i. Passing property values
ii. Default property values
V. What is component state?
VI. React Hooks
VII. Maintaining state using Hooks
i. Initial state values
ii. Updating state values
VIII. Performing initialization and cleanup actions
i. Fetching component data
ii. Canceling actions and resetting state
iii. Optimizing side-effect actions
IX. Sharing data using context Hooks
X. Memoization with Hooks
i. useMemo Hook
ii. useCallback Hook
iii. useRef Hook
XI. Summary
5. 4 Event Handling, the React Way
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Declaring event handlers
i. Declaring handler functions
ii. Multiple event handlers
IV. Declaring inline event handlers
V. Binding handlers to elements
VI. Using synthetic event objects
VII. Understanding event pooling
VIII. Summary
6. 5 Crafting Reusable Components
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Reusable HTML elements
IV. The difficulty with monolithic components
i. The JSX markup
ii. Initial state
iii. Event handler implementation
V. Refactoring component structures
i. Starting with the JSX
ii. Implementing an article list component
iii. Implementing an article item component
iv. Implementing an add article component
VI. Render props
VII. Rendering component trees
VIII. Feature components and utility components
IX. Summary
7. 6 Type Checking and Validation with TypeScript
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Knowing What to Expect
i. The Importance of Props Validation
ii. Potential Issues Without Proper Validation
iii. Options for Props Validation
IV. Introduction to TypeScript
i. Why Use TypeScript?
ii. Setting Up TypeScript in a Project
iii. Basic Types in TypeScript
iv. Interfaces and Type Aliases
V. Comparing PropTypes and TypeScript
VI. Using TypeScript in React
i. Type Checking Props in React Components
ii. Typing State
iii. Typing Event Handlers
iv. Typing Context
v. Typing Refs
VII. Summary
8. 7 Handling Navigation with Routes
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Declaring routes
i. Hello route
ii. Decoupling route declarations
IV. Handling route parameters
i. Resource IDs in routes
ii. Query parameters
V. Using link components
i. Basic linking
ii. URL and query parameters
VI. Summary
9. 8 Code Splitting Using Lazy Components and Suspense
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Using the lazy API
i. Dynamic imports and bundles
ii. Making components lazy
IV. Using the Suspense component
i. Top-level Suspense components
ii. Working with spinner fallbacks
V. Avoiding lazy components
VI. Exploring lazy pages and routes
VII. Summary
10. 9 User Interface Framework Components
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Layout and organization
i. Using containers
ii. Building responsive grid layouts
IV. Using navigation components
i. Navigating with drawers
ii. Navigating with tabs
V. Collecting user input
i. Checkboxes and radio buttons
ii. Text inputs and select inputs
iii. Working with buttons
VI. Working with styles and themes
i. Making styles
ii. Customizing themes
VII. Summary
11. 10 High-Performance State Updates
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Batching state updates
IV. Prioritizing state updates
V. Handling asynchronous state updates
VI. Summary
12. 15 Why React Native?
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. What is React Native?
IV. React and JSX are familiar
V. The mobile browser experiences
VI. Android and iOS – different yet the same
VII. The case for mobile web apps
VIII. Summary
13. 16 React Native under the Hood
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Exploring React Native architecture
i. The state of web and mobile apps in the past
ii. React Native current architecture
iii. React Native future architecture
IV. Explaining JS and Native modules
i. React Navigation
ii. UI component libraries
iii. Splash screen
iv. Icons
v. Handling errors
vi. Push notifications
vii. Over the air updates
viii. JS libraries
V. Exploring React Native components and APIs
VI. Summary
14. 17 Kick-Starting React Native Projects
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Exploring React Native CLI tools
IV. Installing and using the Expo command-line tool
V. Viewing your app on your phone
VI. Viewing your app on Expo Snack
VII. Summary
15. 18 Building Responsive Layouts with Flexbox
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Introducing Flexbox
IV. Introducing React Native styles
V. Using the Styled Components library
VI. Building Flexbox layouts
i. Simple three-column layout
ii. Improved three-column layout
iii. Flexible rows
iv. Flexible grids
v. Flexible rows and columns
VII. Summary
16. 19 Navigating Between Screens
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Navigation basics
IV. Route parameters
V. The navigation header
VI. Tab and drawer navigation
VII. File-based navigation
VIII. Summary
17. 20 Rendering Item Lists
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Rendering data collections
IV. Sorting and filtering lists
V. Fetching list data
VI. Lazy list loading
VII. Implementing pull to refresh
VIII. Summary
18. 21 Showing Progress
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Understanding progress and usability
IV. Indicating progress
V. Measuring progress
VI. Exploring navigation indicators
VII. Step progress
VIII. Summary
19. 22 Geolocation and Maps
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Using Location API
IV. Rendering the Map
V. Annotating points of interest
i. Plotting points
ii. Plotting overlays
VI. Summary
20. 23 Collecting User Input
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Collecting text input
IV. Selecting from a list of options
V. Toggling between on and off
VI. Collecting date/time input
VII. Summary
21. 24 Displaying Modal Screens
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Important information
IV. Getting user confirmation
i. Displaying a success confirmation
V. Error confirmation
VI. Passive notifications
VII. Activity modals
VIII. Summary
22. 25 Responding to User Gestures
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Scrolling with your fingers
IV. Giving touch feedback
V. Using Swipeable and cancellable components
VI. Summary
23. 26 Using Animations
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Using React Native Reanimated
i. Animated API
ii. React Native Reanimated
IV. Installing the React Native Reanimated library
V. Animating layout components
VI. Animating styling components
VII. Summary
24. 27 Controlling Image Display
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Loading images
IV. Resizing images
V. Lazy image loading
VI. Rendering icons
VII. Summary
25. 29 Selecting Native UI Components Using Tamagui
I. Before you begin: Join our book community on Discord
II. Technical requirements
III. Application containers
IV. Headers and footers
V. Using layout components
VI. Collecting input using form components
VII. Summary
VIII. Further reading
React and React Native, Fifth
Edition: Build cross-platform
JavaScript and TypeScript apps for
the web, desktop, and mobile
Welcome to Packt Early Access. We’re giving you an exclusive preview of
this book before it goes on sale. It can take many months to write a book, but
our authors have cutting-edge information to share with you today. Early
Access gives you an insight into the latest developments by making chapter
drafts available. The chapters may be a little rough around the edges right
now, but our authors will update them over time.You can dip in and out
of this book or follow along from start to finish; Early Access is designed to
be flexible. We hope you enjoy getting to know more about the process of
writing a Packt book.

1. Chapter 1: Why React?


2. Chapter 2: Rendering with JSX
3. Chapter 3: Understanding React Components and Hooks
4. Chapter 4: Event Handling, the React Way
5. Chapter 5: Crafting Reusable Components
6. Chapter 6: Type Checking and Validation with TypeScript
7. Chapter 7: Handling Navigation with Routes
8. Chapter 8: Code Splitting Using Lazy Components and Suspense
9. Chapter 9: User Interface Framework Components
10. Chapter 10: High-Performance State Updates
11. Chapter 11: User Interface Framework Components
12. Chapter 12: High-Performance State Updates
13. Chapter 13: Unit Testing in React
14. Chapter 14: Server Rendering and Static Site Generation with React
Frameworks
15. Chapter 15: Why React Native?
16. Chapter 16: React Native under the Hood
17. Chapter 17: Kick-Starting React Native Projects
18. Chapter 18: Building Responsive Layouts with Flexbox
19. Chapter19: Navigating Between Screens
20. Chapter20: Rendering Item Lists
21. Chapter 21: Showing Progress
22. Chapter 22: Geolocation and Maps
23. Chapter 23: Collecting User Input
24. Chapter 24: Displaying Modal Screens
25. Chapter 25: Responding to User Gestures
26. Chapter 26: Using Animations
27. Chapter 27: Controlling Image Display
28. Chapter 28: Going Offline
29. Chapter 29: Selecting Native UI Components Using Tamagui
1 Why React?
Before you begin: Join our book community on
Discord
Give your feedback straight to the author himself and chat to other early
readers on our Discord server (find the "react-and-react-native-5e" channel
under EARLY ACCESS SUBSCRIPTION).

https://packt.link/EarlyAccess

If you're reading this book, you probably know what React is. If not, don't
worry. I'll do my best to keep philosophical definitions to a minimum.
However, this is a long book with a lot of content, so I feel that setting the
tone is an appropriate first step. Yes, the goal is to learn React and React
Native. But it's also to put together a lasting architecture that can handle
everything we want to build with React today and in the future.This chapter
starts with a brief explanation of why React exists. Then, we'll think about
the simplicity of React and how it is able to handle many of the typical
performance issues faced by web developers. Next, we'll go over the
declarative philosophy of React and the level of abstraction that React
programmers can expect to work with. Finally, we'll touch on some of the
major features of React.Once you have a conceptual understanding of React
and how it solves problems with UI development, you'll be better equipped
to tackle the remainder of the book. This chapter will cover the following
topics:

What is React?
React features
What's new in React?
Setting up a new React project

What is React?
I think the one-line description of React on its home page (https://react.dev/)
is concise and accurate:

"A JavaScript library for building user interfaces."

It's a library for building User Interfaces (UIs). This is perfect because, as
it turns out, this is all we want most of the time. I think the best part about this
description is everything that it leaves out. It's not a mega framework. It's not
a full-stack solution that's going to handle everything from the database to
real-time updates over WebSocket connections. We might not actually want
most of these prepackaged solutions. If React isn't a framework, then what is
it exactly?

React is just the view layer


React is generally thought of as the view layer in an application. You might
have used a library such as Handlebars or jQuery in the past. Just as jQuery
manipulates UI elements and Handlebars templates are inserted into a page,
React components change what the user sees. The following diagram
illustrates where React fits in our frontend code:
Figure 1.1 - The layers of a React application

This is all there is to React – the core concept. Of course, there will be
subtle variations to this theme as we make our way through the book, but the
flow is more or less the same. We have some application logic that generates
some data. We want to render this data to the UI, so we pass it to a React
Component, which handles the job of getting the HTML into the page.You
may wonder what the big deal is; React appears to be yet another rendering
technology. We'll touch on some of the key areas where React can simplify
application development in the remaining sections of the chapter.

Simplicity is good
React doesn't have many moving parts to learn about and understand.
Internally, there's a lot going on, and we'll touch on these things throughout
the book. The advantage of having a small API to work with is that you can
spend more time familiarizing yourself with it, experimenting with it, and so
on. The opposite is true of large frameworks, where all of your time is
devoted to figuring out how everything works. The following diagram gives
you a rough idea of the APIs that we have to think about when programming
with React:

Figure 1.2 - The simplicity of the React API

React is divided into two major APIs:

The React Component API: These are the parts of the page that are
rendered by the React DOM.
React DOM: This is the API that's used to perform the rendering on a
web page.

Within a React component, we have the following areas to think about:


Data: This is data that comes from somewhere (the component doesn't
care where) and is rendered by the component.
Lifecycle: This consists of methods or Hooks that we implement to
respond to the component's entering and exiting phases of the React
rendering process as they happen over time – for example, one phase of
the life cycle is when the component is about to be rendered.
Events: These are the code that we write for responding to user
interactions.
JSX: This is the syntax of React components used to describe UI
structures.

Don't fixate on what these different areas of the React API represent just yet.
The takeaway here is that React, by nature, is simple. Just look at how little
there is to figure out! This means that we don't have to spend a ton of time
going through API details here. Instead, once you pick up on the basics, we
can spend more time on nuanced React usage patterns that fit in nicely with
declarative UI structures.

Declarative UI structures
React newcomers have a hard time getting to grips with the idea that
components mix in markup with their JavaScript in order to declare UI
structures. If you've looked at React examples and had the same adverse
reaction, don't worry. Initially, we're all skeptical of this approach, and I
think the reason is that we've been conditioned for decades by the separation
of concerns principle. This principle states that different concerns, such as
logic and presentation, should be separate from one another. Now, whenever
we see things mixed together, we automatically assume that this is bad and
shouldn't happen.The syntax used by React components is called JSX
(JavaScript XML). A component renders content by returning some JSX. The
JSX itself is usually HTML markup, mixed with custom tags for React
components. The specifics don't matter at this point; we'll go into detail in the
coming chapters. What's groundbreaking about the declarative JSX approach
is that we don't have to perform little micro-operations to change the content
of a component.

IMPORTANT NOTE
Although I won't be following the convention in this book, some
React developers prefer the .jsx extension instead of .js for their
components.

For example, think about using something such as jQuery to build your
application. You have a page with some content on it, and you want to add a
class to a paragraph when a button is clicked. Performing these steps is easy
enough. This is called imperative programming, and it's problematic for UI
development. While this example of changing the class of an element is
simple, real applications tend to involve more than three or four steps to
make something happen.React components don't require you to execute steps
in an imperative way. This is why JSX is central to React components. The
XML-style syntax makes it easy to describe what the UI should look like –
that is, what are the HTML elements that this component is going to render?
This is called declarative programming and is very well suited for UI
development. Once you've declared your UI structure, you need to specify
how it changes over time.

Data changes over time


Another area that's difficult for React newcomers to grasp is the idea that
JSX is like a static string, representing a chunk of rendered output. This is
where time and data come into play. React components rely on data being
passed into them. This data represents the dynamic parts of the UI – for
example, a UI element that's rendered based on a Boolean value could
change the next time the component is rendered. Here's a diagram illustrating
the idea:
Figure 1.3 - React components changing over time

Each time the React component is rendered, it's like taking a snapshot of the
JSX at that exact moment in time. As your application moves forward through
time, you have an ordered collection of rendered UI components. In addition
to declaratively describing what a UI should be, re-rendering the same JSX
content makes things much easier for developers. The challenge is making
sure that React can handle the performance demands of this approach.

Performance matters
Using React to build UIs means that we can declare the structure of the UI
with JSX. This is less error-prone than the imperative approach of
assembling the UI piece by piece. However, the declarative approach does
present a challenge –performance.For example, having a declarative UI
structure is fine for the initial rendering because there's nothing on the page
yet. So, the React renderer can look at the structure declared in JSX and
render it in the DOM browser.
IMPORTANT NOTE

The Document Object Model (DOM) represents HTML in the


browser after it has been rendered. The DOM API is how
JavaScript is able to change content on a page.

This concept is illustrated in the following diagram:

Figure 1.4 - How JSX syntax translates to HTML in the browser DOM

On the initial render, React components and their JSX are no different from
other template libraries. For instance, Handlebars will render a template to
HTML markup as a string, which is then inserted into the browser DOM.
Where React is different from libraries such as Handlebars is when data
changes and we need to re-render the component. Handlebars will just
rebuild the entire HTML string, the same way it did on the initial render.
Since this is problematic for performance, we often end up implementing
imperative workarounds that manually update tiny bits of the DOM. We end
up with a tangled mess of declarative templates and imperative code to
handle the dynamic aspects of the UI.We don't do this in React. This is what
sets React apart from other view libraries. Components are declarative for
the initial render, and they stay this way even as they're re-rendered. It's what
React does under the hood that makes re-rendering declarative UI structures
possible.React has something called the virtual DOM, which is used to keep
a representation of the real DOM elements in memory. It does this so that
each time we re-render a component, it can compare the new content to the
content that's already displayed on the page. Based on the difference, the
virtual DOM can execute the imperative steps necessary to make the changes.
So, not only do we get to keep our declarative code when we need to update
the UI but React will also make sure that it's done in a performant way.
Here's what this process looks like:

Figure 1.5 – React transpiles JSX syntax into imperative DOM API calls

IMPORTANT NOTE

When you read about React, you'll often see words such as diffing
and patching. Diffing means comparing old content (the previous
state of the UI) with new content (the updated state) to identify the
differences, much like comparing to versions of a document to see
what’s changed. Patching means executing the necessary DOM
operations to render the new content, ensuring that only the specific
changes are made, which is crucial for performance.

As with any other JavaScript library, React is constrained by the run-to-


completion nature of the main thread. For example, if the React internals are
busy diffing content and patching the DOM, the browser can't respond to user
input. As you'll see in the last section of this chapter, changes were made to
the internal rendering algorithms in React to mitigate these performance
pitfalls. With performance concerns addressed, we need to make sure that
we're confident that React is flexible enough to adapt to different platforms
that we might want to deploy our apps to in the future.

The right level of abstraction


Another topic I want to cover at a high level before we dive into React code
is abstraction.In the preceding section, you saw how JSX syntax translates
to low-level operations that update our UI. A better way to look at how
React translates our declarative UI components is via the fact that we don't
necessarily care what the render target is. The render target happens to be the
browser DOM with React, but it isn't restricted to the browser DOM.React
has the potential to be used for any UI we want to create, on any conceivable
device. We're only just starting to see this with React Native, but the
possibilities are endless. I personally will not be surprised if React Toast
becomes a thing, targeting toasters that can singe the rendered output of JSX
onto bread. The abstraction level with React is at the right level, and it's in
the right place.The following diagram gives you an idea of how React can
target more than just the browser:

Figure 1.6 – React abstracts the target rendering environment from the
components that we implement

From left to right, we have React DOM, React Native, React PDF, and
React Unity. All of these React Renderer libraries, the accepts React
Component and return platform specific result. As you can see, to target
something new, the same pattern applies:

Implement components specific to the target.


Implement a React renderer that can perform the platform-specific
operations under the hood.

This is, obviously, an oversimplification of what's actually implemented for


any given React environment. But the details aren't so important to us. What's
important is that we can use our React knowledge to focus on describing the
structure of our UI on any platform.Now that you understand the role of
abstractions in React, let's see what's new in React.

What's new in React?


React is a continuously evolving library in the ever-changing web
development landscape. As you embark on your journey to learn and master
React, it's important to understand the evolution of the library and its updates
over time. One of the advantages of React, its core API has remained
relatively stable in recent years. This provides a sense of continuity and
allows developers to leverage their knowledge from previous versions. The
conceptual foundation of React has remained intact, meaning that the skills
acquired three or five years ago can still be applied today. Let's take a step
back and trace the history of React from its early versions to the recent. From
React 0.x to React 18, numerous pivotal changes and enhancements have
been made as follows:

React 0.14: In this version, the introduction of functional components


allowed developers to utilize functions as components, simplifying the
creation of basic UI elements. At that time, no one knew that now we
would write only functional components and almost completely abandon
class-based components.
React 15: With a new versioning scheme, the next update of React 15
brought a complete overhaul of the internal architecture, resulting in
improved performance and stability.
React 16: This version, however, stands as one of the most notable
releases in React's history. It introduced hooks, a revolutionary concept
that enables developers to use state and other React features without the
need for class components. Hooks make code simpler and more
readable, transforming the way developers write components. We will
explore a lot of hooks in this book. Additionally, React 16 introduced
Fiber, a new reconciliation mechanism that significantly improved
performance, especially when dealing with animations and complex UI
structures.
React 17: This version focused on updating and maintaining
compatibility with previous versions. It introduced a new JSX
transform system.
React 18: This is the latest, stable release, which continues the
trajectory of improvement, and emphasizes performance enhancements
and additional features such as automatic batching of renders, state
transitions, server components, and streaming server-side rendering.
Most of the important updates related to performance will be explored
in Chapter 12, High-Performance State Updates. More details about
server rendering will be covered in Chapter 14, Server Rendering and
Static Site Generation with React Frameworks.

React's stability and compatibility make it a reliable library for long-term


use, while the continuous updates ensure that it remains at the forefront of
web and mobile development. Throughout this book, all examples will
utilize the latest React API, ensuring that they remain functional and relevant
in future versions. Now that we have explored the evolution and updates in
React, we can delve deeper into React, and examine how to get set up with
the new React project.

Setup a new React project


There are several ways to create a React project when you are getting started
or learning. In this section, we will explore three common approaches:

Using Web Bundlers


Using Frameworks
Online Code Editors
To start developing and previewing your React applications, you will
first need to have Node.js installed on your computer. Node.js is a
runtime environment for executing JavaScript code.

Let's dive into each approach in the following subsections.

Using Web Bundlers


Using a web bundler is an efficient way to create React projects, especially
if you are building a Single Page Application (SPA). For all of the examples
in this book, we will use Vite as our web bundler. Vite is known for its
remarkable speed and ease of setup and use.To set up your project using Vite,
you will need to take the following steps:

1. Ensure that you have Node.js installed on your computer by visiting the
official Node.js website and downloading the appropriate version for
your operating system.
2. Open your terminal or command prompt and navigate to the directory
where you want to create your project.
3. Run the following command to create a new React project with Vite:
npm create vite@latest my-vue-app -- --template vue

This command creates a new directory called my-react-app and sets up a


React project using the Vite template.

1. Once the project is created, navigate into the project directory:

cd my-react-app

1. Install dependencies:

npm install

1. Finally, start the development server by running the following


command:
npm run dev
This command launches the development server, and you can view your
React application by opening your browser and visiting
http://localhost:3000.By now, you would have successfully set up your React
project using Vite as the web bundler. For more information about Vite and
possible configurations, visit the official website at https://vitejs.dev/.

Using Frameworks
For real-world and commercial projects, it is recommended to use
frameworks built on top of React. These frameworks provide additional
features out of the box, such as routing and asset management (images, SVG
files, fonts, etc.). They also guide you in organizing your project structure
effectively, as frameworks often enforce specific file organization rules.
Some popular React frameworks include Next.js, Gatsby, and Remix.In
Chapter 14, Server Rendering and Static Site Generation with React
Frameworks, we will explore NextJS setup and some differences between
using web bundlers.

Online Code Editors


Online code editors combine the advantages of web bundlers and
frameworks but allow you to set up your React development environment in
the cloud or right inside of the browser. This eliminates the need to install
anything on your machine and lets you write and explore React code directly
in your browser.While there are various online code editors available, some
popular options include CodeSandbox, StackBlitz, and Replit. These
platforms provide a user-friendly interface and allow you to create, share,
and collaborate on React projects without any local setup.To get started with
an online code editor, you even don’t need an account. Try to open the link on
your browser at https://react.new. In a few seconds you will see that
CodeSandbox is ready to work project with live preview. To save your
work, you need to create an account. Using online code editors is a
convenient way to learn and experiment with React, especially if you prefer
a browser-based development environment.In this section, we explored
different methods for setting up your React project. Whether you choose web
bundlers, frameworks, or online code editors, each approach offers its
unique advantages. Select the method that you prefer and suits your project
requirements, and let's dive into the world of React development!

Summary
In this chapter, you were introduced to React at a high level. React is a
library with a small API used to build UIs. Next, you were introduced to
some of the key concepts of React. We discussed the fact that React is simple
because it doesn't have a lot of moving parts. Afterward, we explored the
declarative nature of React components and JSX. Following that, you learned
that React takes performance seriously, enabling us to write declarative code
that can be re-rendered repeatedly. You also gained insight into the idea of
render targets and how React can easily become the UI tool of choice for all
of them. I then provided you with a brief overview of React’s history and
introduced latest developments. Finally, we delved into how to set up a new
React project and initiate the learning process.That's sufficient introductory
and conceptual content for now. As we progress through the book’s journey,
we'll revisit these concepts. Next, let's take a step back and nail down the
basics, starting with JSX in the next chapter.
2 Rendering with JSX
Before you begin: Join our book community on Discord
Give your feedback straight to the author himself and chat to other early readers on
our Discord server (find the "react-and-react-native-5e" channel under EARLY
ACCESS SUBSCRIPTION).

https://packt.link/EarlyAccess

This chapter will introduce you to JSX, which is the XML/HTML markup syntax
that's embedded in your JavaScript code and used to declare your React
components. At the lowest level, you'll use HTML markup to describe the pieces
of your UI. Building React applications involves organizing these pieces of HTML
markup into components. When you create a component, you add new vocabulary
to JSX beyond basic HTML markup. This is where React gets interesting – when
you have your own JSX tags that can use JavaScript expressions to bring your
components to life. JSX is the language used to describe UIs built using React.In
this chapter, we'll cover the following:

Your first JSX content


Rendering HTML
Describing the UI structure
Creating your own JSX elements
Using JavaScript expressions
Fragments of JSX

Technical requirements
The code for this chapter can be found in the following directory of the
accompanying GitHub repository: https://github.com/PacktPublishing/React-and-
React-Native-5E/tree/main/Chapter02.

Your first JSX content


In this section, we'll implement the obligatory " Hello, World " JSX application.
At this point, we're just dipping our toes in the water; more in-depth examples will
follow. We'll also discuss what makes this syntax work well for declarative UI
structures.

Hello JSX
Without further ado, here's your first JSX application:

import * as ReactDOM from "react-dom";


const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<p>
Hello, <strong>JSX</strong>
</p>
);

Let's walk through what's happening here. The render() function takes JSX as an
argument and renders it to the DOM node passed to
ReactDOM.createRoot() .The actual JSX content in this example renders a
paragraph with some bold text inside. There's nothing fancy going on here, so we
could have just inserted this markup into the DOM directly as a plain string.
However, the aim of this example is to show the basic steps involved in getting
JSX rendered onto the page. Now, let's talk a little bit about the declarative UI
structure.

IMPORTANT NOTE

JSX is transpiled into JavaScript statements; browsers have no idea


what JSX is. I would highly recommend downloading the companion
code for this book from https://github.com/PacktPublishing/React-and-
React-Native-5E and running it as you read along. Everything transpiles
automatically for you; you just need to follow the simple installation
steps.

Declarative UI structures
Before we move forward with more in-depth code examples, let's take a moment to
reflect on our " Hello, World " example. The JSX content was short and simple.
It was also declarative because it described what to render, not how to render it.
Specifically, by looking at the JSX, you can see that this component will render a
paragraph and some bold text within it. If this were done imperatively, there would
probably be some more steps involved, and they would probably need to be
performed in a specific order.

IMPORTANT NOTE

I find it helpful to think of declarative as structured and imperative as


ordered. It's much easier to get things right with a proper structure than to
perform steps in a specific order.

The example we just implemented should give you a feel for what declarative
React is all about. As we move forward in this chapter and throughout the book, the
JSX markup will grow more elaborate. However, it's always going to describe
what is in the UI.The render() function tells React to take your JSX markup and
transform it into JavaScript statements that update the UI in the most efficient way
possible. This is how React enables you to declare the structure of your UI without
having to think about carrying out ordered steps to update elements on the screen;
an approach that often leads to bugs. Out of the box, React supports the standard
HTML tags that you would find on any HTML page. Unlike static HTML, React
has unique conventions that should be followed when using HTML tags.…

Rendering HTML
At the end of the day, the job of a React component is to render HTML into the
DOM browser. This is why JSX has support for HTML tags out of the box. In this
section, we'll look at some code that renders a few of the available HTML tags.
Then, we'll cover some of the conventions that are typically followed in React
projects when HTML tags are used.

Built-in HTML tags


When we render JSX, element tags reference React components. Since it would be
tedious to have to create components for HTML elements, React comes with
HTML components. We can render any HTML tag in our JSX, and the output will
be just as we'd expect. Now, let's try rendering some of these tags:
import * as ReactDOM from "react-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<div>
<button />
<code />
<input />
<label />
<p />
<pre />
<select />
<table />
<ul />
</div>
);

Don't worry about the formatting of the rendered output for this example. We're
making sure that we can render arbitrary HTML tags, and they render as expected,
without any special definitions and imports.

IMPORTANT NOTE

You may have noticed the surrounding <div> tag, grouping together all
of the other tags as its children. This is because React needs a root
element to render. Later in the chapter, you'll learn how to render
adjacent elements without wrapping them in a parent element.

HTML elements rendered using JSX closely follow regular HTML element syntax
with a few subtle differences regarding case-sensitivity and attributes.

HTML tag conventions


When you render HTML tags in JSX markup, the expectation is that you'll use
lowercase for the tag name. In fact, capitalizing the name of an HTML tag will fail.
Tag names are case-sensitive and non-HTML elements are capitalized. This way,
it's easy to scan the markup and spot the built-in HTML elements versus everything
else.You can also pass HTML elements any of their standard properties. When you
pass them something unexpected, a warning about the unknown property is logged.
Here's an example that illustrates these ideas:

import * as ReactDOM from "react-dom";


const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<button title="My Button" foo="bar">
My Button
</button>
);
root.render(<Button />);

When you run this example, it will fail to compile because React doesn't know
about the <Button> element; it only knows about <button> .

IMPORTANT NOTE

Later on in the book, I'll cover property validation for the components
that you make. This avoids silent misbehavior, as seen with the foo
property in this example.

You can use any valid HTML tags as JSX tags, as long as you remember that
they're case-sensitive and that you need to pass the correct attribute names. In
addition to simple HTML tags that only have attribute values, you can use HTML
tags to describe the structure of your page content.

Describing UI structures
JSX is capable of describing screen elements in a way that ties them together to
form a complete UI structure. Let's look at some JSX markup that declares a more
elaborate structure than a single paragraph:
import * as ReactDOM from "react-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<section>
<header>
<h1>A Header</h1>
</header>
<nav>
<a href="item">Nav Item</a>
</nav>
<main>
<p>The main content...</p>
</main>
<footer>
<small>&copy; 2024</small>
</footer>
</section>
);

This JSX markup describes a fairly sophisticated UI structure. Yet, it's easier to
read than imperative code because it's XML, and XML is good for concisely
expressing a hierarchical structure. This is how we want to think of our UI when it
needs to change – not as an individual element or property, but the UI as a
whole.Here is what the rendered content looks like:

Figure 2.1 - Describing HTML tag structures using JSX syntax

There are a lot of semantic elements in this markup describing the structure of the
UI. For example, the <header> element describes the top part of the page where
the title is, and the <main> element describes where the main page content goes.
This type of complex structure makes it clearer for developers to reason about. But
before we start implementing dynamic JSX markup, let's create some of our own
JSX components.

Creating your own JSX elements


Components are the fundamental building blocks of React. In fact, components are
the vocabulary of JSX markup. In this section, we'll see how to encapsulate HTML
markup within a component. We'll build examples that nest custom JSX elements
and learn how to namespace components.

Encapsulating HTML
We create new JSX elements so that we can encapsulate larger structures. This
means that instead of having to type out complex markup, you can use your custom
tag. The React component returns the JSX that goes where the tag is used. Let's
look at the following example:
import * as ReactDOM from "react-dom";
function MyComponent() {
return (
<section>
<h1>My Component</h1>
<p>Content in my component...</p>
</section>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<MyComponent />);

Here's what the rendered output looks like:

Figure 2.2 - A component rendering encapsulated HTML markup

This is the first React component that we've implemented, so let's take a moment to
dissect what's going on here. We created a function called MyComponent , where in
return statement we put our HTML tags. This is how we create a new JSX element.
As you can see in the call to render() , you're rendering a <MyComponent>
element.The HTML that this component encapsulates is returned from the function
we created. In this case, when the JSX is rendered by react-dom , it's replaced by
a <section> element and everything within it.

IMPORTANT NOTE

When React renders JSX, any custom elements that you use must have
their corresponding React component within the same scope. In the
preceding example, the MyComponent function was declared in the same
scope as the call to render() , so everything worked as expected.
Usually, you'll import components, adding them to the appropriate scope.
You'll see more of this as you progress through the book.
HTML elements such as <div> often take nested child elements. Let's see whether
we can do the same with JSX elements, which we create by implementing
components.

Nested elements
Using JSX markup is useful for describing UI structures that have parent-child
relationships. Child elements are created by nesting them within another
component: the parent. For example, a <li> tag is only useful as the child of a
<ul> tag or a <ol> tag—you're probably going to make similar nested structures
with your own React components. For this, you need to use the children
property. Let's see how this works. Here's the JSX markup:
import * as ReactDOM from "react-dom";
import MySection from "./MySection";
import MyButton from "./MyButton";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<MySection>
<MyButton>My Button Text</MyButton>
</MySection>
);

You're importing two of your own React components: MySection and MyButton .
Now, if you look at the JSX markup, you'll notice that <MyButton> is a child of
<MySection> . You'll also notice that the MyButton component accepts text as its
child, instead of more JSX elements. Let's see how these components work,
starting with MySection :
export default function MySection(props) {
return (
<section>
<h2>My Section</h2>
{props.children}
</section>
);
}

This component renders a standard <section> HTML element, a heading, and


then {props.children} . It's this last piece that allows components to access
nested elements or text, and to render them.

IMPORTANT NOTE
The two braces used in the preceding example are used for JavaScript
expressions. I'll touch on more details of the JavaScript expression
syntax found in JSX markup in the following section.

Now, let's look at the MyButton component:


export default function MyButton(props) {
return <button>{props.children}</button>;
}

This component uses the exact same pattern as MySection ; it takes the
{props.children} value and surrounds it with markup. React handles the details
for you. In this example, the button text is a child of MyButton , which is, in turn, a
child of MySection . However, the button text is transparently passed through
MySection . In other words, we didn't have to write any code in MySection to
make sure that MyButton got its text. Pretty cool, right? Here's what the rendered
output looks like:

Figure 2.3 - A button element rendered using child JSX values

We can further organize our components by placing them within a namespace.

Namespaced components
The custom elements that you've created so far have used simple names. A
namespace provides an organizational unit for your components so that related
components can share the same namespace prefix. Instead of writing
<MyComponent> in your JSX markup, you would write
<MyNamespace.MyComponent> . This makes it clear that MyComponent is part of
MyNamespace .Typically, MyNamespace would also be a component. The idea of
namespacing is to have a namespace component render its child components using
the namespace syntax. Let's take a look at an example:

import * as ReactDOM from "react-dom";


import MyComponent from "./MyComponent";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<MyComponent>
<MyComponent.First />
<MyComponent.Second />
</MyComponent>
);

This markup renders a <MyComponent> element with two children. Instead of


writing <First> , we write <MyComponent.First> , and the same with
<MyComponent.Second> . We want to explicitly show that First and Second
belong to MyComponent within the markup.Now, let's take a look at the
MyComponent module:

function First() {
return <p>First...</p>;
}
function Second() {
return <p>Second...</p>;
}
function MyComponent(props) {
return <section>{props.children}</section>;
}
MyComponent.First = First;
MyComponent.Second = Second;
export default MyComponent;
export { First, Second };

This module declares MyComponent as well as the other components that fall
under this namespace ( First and Second ). It assigns the components to the
namespace component ( MyComponent ) as function object properties. There are a
number of things that you could change in this module. For example, you don't have
to directly export First and Second since they're accessible through
MyComponent . You also don't need to define everything in the same module; you
could import First and Second and assign them as function object properties.
Using namespaces is completely optional, and, if you use them, you should use
them consistently.You now know how to build your own React components that
introduce new JSX tags in your markup. The components that we've looked at so
far in this chapter have been static. That is, once we rendered them, they were
never updated. JavaScript expressions are the dynamic pieces of JSX and are what
cause React to update components.

Using JavaScript expressions


As you saw in the preceding section, JSX has a special syntax that allows you to
embed JavaScript expressions. Any time React renders JSX content, expressions in
the markup are evaluated. This is the dynamic aspect of JSX, and in this section,
you'll learn how to use expressions to set property values and element text content.
You'll also learn how to map collections of data to JSX elements.

Dynamic property values and text


Some HTML property or text values are static, meaning that they don't change as
JSX markup is re-rendered. Other values, the values of properties or text, are
based on data that is found elsewhere in the application. Remember, React is just
the view layer. Let's look at an example so that you can get a feel for what the
JavaScript expression syntax looks like in JSX markup:
import * as ReactDOM from "react-dom";
const enabled = false;
const text = "A Button";
const placeholder = "input value...";
const size = 50;
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<section>
<button disabled={!enabled}>{text}</button>
<input placeholder={placeholder} size={size} />
</section>
);

Anything that is a valid JavaScript expression, including nested JSX, can go in


between the curly braces: {} . For properties and text, this is often a variable name
or object property. Notice, in this example, that the !enabled expression
computes a Boolean value. Here's what the rendered output looks like:
Figure 2.4 - Dynamically changing the property value of a button

IMPORTANT NOTE

If you're following along with the downloadable companion code, which


I strongly recommend doing, try playing with these values and seeing
how the rendered HTML changes.

Primitive JavaScript values are straightforward to use in JSX syntax. But what if
you have an object or array that you need to transform into JSX elements?

Handling events
In React, you can easily pass events to components to handle user interactions such
as button clicks, form submissions, and mouse movements. This allows you to
create interactive and responsive user interfaces. React provides a convenient way
to attach event handlers directly to components using a syntax similar to how you
would use the addEventListener and removeEventListener methods in
traditional JavaScript.To illustrate this, let's consider an example where we want
to handle a button click event in a React component:
import * as ReactDOM from "react-dom";
const handleClick = () => {
console.log("Button clicked!");
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<section>
<button onClick={handleClick}>Click me</button>
</section>
);

In this example, we define a function called handleClick that will be called


when the button is clicked. We then attach this function as an event handler to the
onClick property of the <button> component. Whenever the button is clicked,
React will invoke the handleClick function.Compared to using
addEventListener and removeEventListener in traditional JavaScript, React
abstracts away some of the complexities. With React's event handling, you don't
have to worry about manually attaching and detaching event listeners to DOM
elements. React manages the event delegation and provides a more declarative
approach to handling events within components.By using this approach, you can
easily pass events to child components, handle them in parent components, or even
propagate events through multiple levels of nested components. This helps in
building a modular and reusable component architecture.It's important to note that
when defining event handlers in React, you don't invoke the function immediately
by adding parentheses after the function name, as you would in regular JavaScript.
Instead, you provide a reference to the function, allowing React to call it when the
event occurs.

In addition to the onClick event, React supports a wide range of other


events, such as onChange , onSubmit , onMouseOver , and many more. You
can attach event handlers to various elements like buttons, input fields,
checkboxes, and so on.

Remember, React promotes a unidirectional data flow, which means that data
flows from parent components to child components. To pass data or information
from child components back to the parent component, you can define callbacks as
props and invoke them with the necessary data. In the upcoming chapters of this
book, we will delve deeper into event handling in React and how to create custom
callbacks.

Mapping collections to elements


Sometimes, you need to write JavaScript expressions that change the structure of
your markup. In the preceding section, you learned how to use JavaScript
expression syntax to dynamically change the property values of JSX elements.
What about when you need to add or remove elements based on JavaScript
collections?

IMPORTANT NOTE

Throughout the book, when I refer to a JavaScript collection, I'm


referring to both plain objects and arrays. Or, more generally, anything
that's iterable.
The best way to dynamically control JSX elements is to map them from a
collection. Let's look at an example of how this is done:
import * as ReactDOM from "react-dom";
const array = ["First", "Second", "Third"];
const object = {
first: 1,
second: 2,
third: 3,
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<section>
<h1>Array</h1>
<ul>
{array.map((i) => (
<li key={i}>{i}</li>
))}
</ul>
<h1>Object</h1>
<ul>
{Object.keys(object).map((i) => (
<li key={i}>
<strong>{i}: </strong>
{object[i]}
</li>
))}
</ul>
</section>
);

The first collection is an array called array, populated with string values. Moving
down to the JSX markup, you can see the call to array.map() , which returns a
new array. The mapping function is actually returning a JSX element ( <li> ),
meaning that each item in the array is now represented in the markup.

IMPORTANT NOTE

The result of evaluating this expression is an array. Don't worry – JSX


knows how to render arrays of elements.

The object collection uses the same technique, except you have to call
Object.keys() and then map this array. What's nice about mapping collections to
JSX elements on the page is that you can control the structure of React components
based on the collected data. This means that you don't have to rely on imperative
logic to control the UI.Here's what the rendered output looks like:
Another random document with
no related content on Scribd:
like articles of Porto Rican manufacture: Provided, That on
and after the date when this Act shall take effect, all
merchandise and articles, except coffee, not dutiable under
the tariff laws of the United States, and all merchandise and
articles entered in Porto Rico free of duty under' orders
heretofore made by the Secretary of War, shall be admitted
into the several ports thereof, when imported from the United
States, free of duty, all laws or parts of laws to the
contrary notwithstanding; and whenever the legislative
assembly of Porto Rico shall have enacted and put into
operation a system of local taxation to meet the necessities
of the government of Porto Rico, by this Act established, and
shall by resolution duly passed so notify the President, he
shall make proclamation thereof, and thereupon all tariff
duties on merchandise and articles going into Porto Rico from
the United States or coming into the United States from Porto
Rico shall cease, and from and after such date all such
merchandise and articles shall be entered at the several ports
of entry free of duty; and in no event shall any duties be
collected after the first day of March, nineteen hundred and
two, on merchandise and articles going into Porto Rico from
the United States or coming into the United States from Porto
Rico.

"SECTION 4.
That the duties and taxes collected in Porto Rico in pursuance
of this Act, less the cost of collecting the same, and the
gross amount of all collections of duties and taxes in the
United States upon articles of merchandise coming from Porto
Rico, shall not be covered into the general fund of the
Treasury, but shall be held as a separate fund, and shall be
placed at the disposal of the President to be used for the
government and benefit of Porto Rico until the government of
Porto Rico herein provided for shall have been organized, when
all moneys theretofore collected under the provisions hereof,
then unexpended, shall be transferred to the local treasury of
Porto Rico, and the Secretary of the Treasury shall designate
the several ports and sub-ports of entry in Porto Rico, and
shall make such rules and regulations and appoint such agents
as may be necessary to collect the duties and taxes authorized
to be levied, collected, and paid in Porto Rico by the
provisions of this Act, and he shall fix the compensation and
provide for the payment thereof of all such officers, agents,
and assistants as he may find it necessary to employ to carry
out the provisions hereof: Provided, however, That as soon as
a civil government for Porto Rico shall have been organized in
accordance with the provisions of this Act and notice thereof
shall have been given to the President he shall make
proclamation thereof, and thereafter all collections of duties
and taxes in Porto Rico under the provisions of this Act shall
be paid into the treasury of Porto Rico, to be expended as
required by law for the government and benefit thereof instead
of being paid into the Treasury of the United States."

PORTO RICO: A. D. 1900 (April).


Act to provide temporarily for the civil government
of the Island.

The fundamental provisions of the act of the Congress of the


United States to provide temporarily for the civil government
of Porto Rico, which the President approved April 12, 1900,
are the following:

"SECTION 6.
That the capital of Porto Rico shall be at the city of San
Juan and the seat of government shall be maintained there.

"SECTION 7.
That all inhabitants continuing to reside therein who were
Spanish subjects on the eleventh day of April, eighteen
hundred and ninety-nine, and then resided in Porto Rico, and
their children born subsequent thereto, shall be deemed and
held to be citizens of Porto Rico, and as such entitled to the
protection of the United States, except such as shall have
elected to preserve their allegiance to the Crown of Spain on
or before the eleventh day of April, nineteen hundred, in
accordance with the provisions of the treaty of peace between
the United States and Spain entered into on the eleventh day
of April, eighteen hundred and ninety-nine; and they, together
with such citizens of the United States as may reside in Porto
Rico, shall constitute a body politic under the name of The
People of Porto Rico, with governmental powers as hereinafter
conferred, and with power to sue and be sued as such.

{416}

"SECTION 8.
That the laws and ordinances of Porto Rico now in force shall
continue in full force and effect, except as altered, amended,
or modified hereinafter, or as altered or modified by military
orders and decrees in force when this Act shall take effect,
and so far as the same are not inconsistent or in conflict
with the statutory laws of the United States not locally
inapplicable, or the provisions hereof, until altered,
amended, or repealed by the legislative authority hereinafter
provided for Porto Rico or by Act of Congress of the United
States: Provided, That so much of the law which was in force
at the time of cession, April eleventh, eighteen hundred and
ninety-nine, forbidding the marriage of priests, ministers, or
followers of any faith because of vows they may have taken,
being paragraph four, article eighty-three, chapter three,
civil code, and which was continued by the order of the
secretary of justice of Porto Rico, dated March seventeenth,
eighteen hundred and ninety-nine, and promulgated by
Major-General Guy V. Henry, United States Volunteers, is
hereby repealed and annulled, and all persons lawfully married
in Porto Rico shall have all the rights and remedies conferred
by law upon parties to either civil or religious marriages:
And provided further, That paragraph one, article one hundred
and five, section four, divorce, civil code, and paragraph
two, section nineteen, of the order of the minister of justice
of Porto Rico, dated March seventeenth, eighteen hundred and
ninety-nine, and promulgated by Major-General Guy V. Henry,
United States Volunteers, be, and the same hereby are, so
amended as to read: 'Adultery on the part of either the
husband or the wife.' …

"SECTION 14.
That the statutory laws of the United States not locally
inapplicable, except as hereinbefore or hereinafter otherwise
provided, shall have the same force and effect in Porto Rico
as in the United States, except the internal-revenue laws,
which, in view of the provisions of section three, shall not
have force and effect in Porto Rico.

"SECTION 15.
That the legislative authority hereinafter provided shall have
power by due enactment to amend, alter, modify, or repeal any
law or ordinance, civil or criminal, continued in force by
this Act, as it may from time to time see fit.

"SECTION 16.
That all judicial process shall run in the name of 'United
States of America, ss: the President of the United States,'
and all criminal or penal prosecutions in the local courts
shall be conducted in the name and by the authority of 'The
People of Porto Rico'; and all officials authorized by this
Act shall before entering upon the duties of their respective
offices take an oath to support the Constitution of the United
States and the laws of Porto Rico.

"SECTION 17.
That the official title of the chief executive officer shall
be 'The Governor of Porto Rico.' He shall be appointed by the
President, by and with the advice and consent of the Senate;
he shall hold his office for a term of four years and until
his successor is chosen and qualified unless sooner removed by
the President; he shall reside in Porto Rico during his
official incumbency, and shall maintain his office at the seat
of government; he may grant pardons and reprieves, and remit
fines and forfeitures for offenses against the laws of Porto
Rico, and respites for offenses against the laws of the United
States, until the decision of the President can be
ascertained; he shall commission all officers that he may be
authorized to appoint, and may veto any legislation enacted,
as hereinafter provided; he shall be the commander in chief of
the militia, and shall at all times faithfully execute the
laws, and he shall in that behalf have all the powers of
governors of the Territories of the United States that are not
locally inapplicable; and he shall annually, and at such other
times as he may be required, make official report of the
transactions of the government in Porto Rico, through the
Secretary of State, to the President of the United States:
Provided, That the President may, in his discretion, delegate
and assign to him such executive duties and functions as may
in pursuance with law be so delegated and assigned.

"SECTION 18.
That there shall be appointed by the President, by and with
the advice and consent of the Senate, for the period of four
years, unless sooner removed by the President, a secretary, an
attorney-general, a treasurer, an auditor, a commissioner of
the interior, and a commissioner of education, each of whom
shall reside in Porto Rico during his official incumbency and
have the powers and duties hereinafter provided for them,
respectively, and who, together with five other persons of
good repute, to be also appointed by the President for a like
term of four years, by and with the advice and consent of the
Senate, shall constitute an executive council, at least five
of whom shall be native inhabitants of Porto Rico, and, in
addition to the legislative duties hereinafter imposed upon
them as a body, shall exercise such powers and perform such
duties as are hereinafter provided for them, respectively, and
who shall have power to employ all necessary deputies and
assistants for the proper discharge of their duties as such
officials and as such executive council. …

"SECTION 27.
That all local legislative powers hereby granted shall be
vested in a legislative assembly which shall consist of two
houses; one the executive council, as hereinbefore
constituted, and the other a house of delegates, to consist of
thirty-five members elected biennially by the qualified voters
as hereinafter provided; and the two houses thus constituted
shall be designated 'The legislative assembly of Porto Rico.'

"SECTION 28.
That for the purposes of such elections Porto Rico shall be
divided by the executive council into seven districts,
composed of contiguous territory and as nearly equal as may be
in population, and each district shall be entitled to five
members of the house of delegates.

SECTION 29.
That the first election for delegates shall be held on such
date and under such regulations as to ballots and voting as
the executive council may prescribe. … At such elections all
citizens of Porto Rico shall be allowed to vote who have been
bona fide residents for one year and who possess the other
qualifications of voters under the laws and military orders in
force on the first day of March, 1900, subject to such
modifications and additional qualifications and such
regulations and restrictions as to registration as may be
prescribed by the executive council. …

{417}

"SECTION 32.
That the legislative authority herein provided shall extend to
all matters of a legislative character not locally inapplicable,
including power to create, consolidate, and reorganize the
municipalities, so far as may be necessary, and to provide and
repeal laws and ordinances therefor; and also the power to
alter, amend, modify, and repeal any and all laws and
ordinances of every character now in force in Porto Rico, or
any municipality or district thereof, not inconsistent with
the provisions hereof: Provided, however, That all grants of
franchises, rights, and privileges or concessions of a public
or quasi-public nature shall be made by the executive council,
with the approval of the governor, and all franchises granted
in Porto Rico shall be reported to Congress, which hereby
reserves the power to annul or modify the same.

"SECTION 33.
That the judicial power shall be vested in the courts and
tribunals of Porto Rico as already established and now in
operation, including municipal courts. …

"SECTION 34.
That Porto Rico shall constitute a judicial district to be
called 'the district of Porto Rico.' The President, by and
with the advice and consent of the Senate, shall appoint a
district judge, a district attorney, and a marshal for said
district, each for a term of four years, unless sooner removed
by the President. The district court for said district shall
be called the district court of the United States for Porto
Rico.

"SECTION 35.
That writs of error and appeals from the final decisions of
the supreme court of Porto Rico and the district court of the
United States shall be allowed and may be taken to the Supreme
Court of the United States in the same manner and under the
same regulations and in the same cases as from the supreme
courts of the Territories of the United States. …

"SECTION 39.
That the qualified voters of Porto Rico shall, on the first
Tuesday after the first Monday of November, anno Domini
nineteen hundred, and every two years thereafter, choose a
resident commissioner to the United States, who shall be
entitled to official recognition as such by all Departments,
upon presentation to the Department of State of a certificate
of election of the governor of Porto Rico, and who shall be
entitled to a salary, payable monthly by the United States, at
the rate of five thousand dollars per annum: Provided, That no
person shall be eligible to such election who is not a bona
fide citizen of Porto Rico, who is not thirty years of age,
and who does not read and write the English language.

"SECTION 40.
That a commission, to consist of three members, at least one
of whom shall be a native citizen of Porto Rico, shall be
appointed by the President, by and with the advice and consent
of the Senate, to compile and revise the laws of Porto Rico; also
the various codes of procedure and systems of municipal
government now in force, and to frame and report such
legislation as may be necessary to make a simple, harmonious,
and economical government, establish justice and secure its
prompt and efficient administration, inaugurate a general
system of education and public instruction, provide buildings
and funds therefor, equalize and simplify taxation and all the
methods of raising revenue, and make all other provisions that
may be necessary to secure and extend the benefits of a
republican form of government to all the inhabitants of Porto
Rico."

PORTO RICO: A. D. 1900 (May).


Organization of civil government.
Appointment of Governor Allen.

Under the Act to establish civil government in Porto Rico,


Honorable. Charles H. Allen, formerly a representative in
Congress from Massachusetts, and lately Assistant-Secretary of
the Navy, was appointed to the governorship of the island. Mr.
J. H. Hollander, of Maryland, was appointed Treasurer, and Mr.
John R. Garrison, of the District of Columbia, Auditor.
Governor Allen was inducted into office with considerable
ceremony, at San Juan, on the 1st of May.

PORTO RICO: A. D. 1900 (August-October).


First steps in the creation of a public school system.

"The report of M. G. Brumbaugh, commissioner of education, on


education in Porto Rico, dated October 15, 1900, shows what
has been accomplished in the short time that elapsed after the
commissioner entered upon his duties on August 4, 1900. … The
people want schools … and the pupils will attend them. In
1899, 616 schools were opened in Porto Rico. In 1900 the
department will maintain at least 800 schools, an increase of
30 per cent, which will provide for nearly 9,000 additional
pupils.

"In 1899 there were 67 Americans in the teaching force of the


island. Since October 1, 1900, the number has increased to
100. The commissioner criticises one class of teachers who are
'seekers after novelty and new experiences, who imposed upon the
administration and the children, and who used the salary and
position of teacher solely to see a new country for a year and
then return. … The people of Porto Rico have patiently borne
with these adventurers, and quietly longed for their
departure.' This class of teachers is now gone and the newly
selected American teachers have some knowledge of Spanish and
are graduates of universities, colleges, and normal schools in
the States, and are for the most part young men and women of
ability and discretion. The salaries of American teachers were
fixed by law at $40 per month for nine months in cities of
less than 5,000 population. In cities of larger population the
salary was $50 per month for nine months and both are
inadequate, although at the time the salaries were fixed the
War Department provided free transportation from and to the
United States. This transportation may now be withdrawn at any
time, and the small inducement held out by the meager salary
offered to teachers is not calculated to invite the best class
of them to the island.

"The new normal and industrial school at Fajardo, which was to


have been established by the joint efforts of the local
municipality and the American Government, was only so far
advanced that the land had been purchased by the end of
September, 1900. The normal department was opened October 1,
in a rented building, while the industrial department cannot
be opened until suitable quarters are provided. The
commissioner recommends that the United States make this place
the site of an agricultural experiment station for which it is
pre-eminently fitted. On account of the industries of the
country—coffee, sugar, tobacco, and fruit—agriculture could be
well studied here, and free boarding, lodging, and tuition would
be given the students, who would be for the most part poor
boys and girls.

"As to the school accommodation, the commissioner states that


there are no public school buildings in Porto Rico. The
schools are conducted in rented houses or rooms which are
often unfit for the purpose, and the hygienic conditions are
bad. There is a wide field, or rather a demand, for
improvement in this direction, as well as in the school
equipment and material.

{418}

In 1899, $33,000 was expended for school-books, and in 1900,


$20,000 will be expended for books and supplies, which shall
be free. In the United States 'free books' means usually their
purchase by local boards and free use by the pupils. In Porto
Rico the books and supplies will be free to the pupils without
expense to the local boards. A pedagogical museum and library
has been established for the benefit of teachers and others.
About 300 volumes have been contributed to the library from
friends in the States, and the Department will make the number
up to 500 by purchase. A library of 5,000 volumes of standard
Spanish and American literature was found in a building in San
Juan, which has been installed in suitable rooms as a public
library.

"Many of the leading institutions of the United States have


responded cordially to the application of the Department of
Education on behalf of young Porto Ricans who wish to
prosecute their studies in colleges and universities. Some
have offered free tuition, some have added free lodging, while
others have offered even free living to all such students as
wish to avail themselves of their instruction. Many young
Porto Ricans have availed themselves of these generous offers.

"There are now 800 schools in Porto Rico, and 38,000 pupils
attending them, while there are 300,000 children of school age
for whom there are no accommodations. But the commissioner
expresses the hope that gradually the great illiteracy in
Porto Rico will be reduced, and the people prepared for the
duties of citizenship in a democracy by means of the schools
that shall be established. … The total expenditure for
education in Porto Rico from the 1st of May to the end of
September was $91,057.32."

United States, Secretary of the Interior,


Annual Report, November 28, 1900, page 116.

PORTO RICO: A. D. 1900 (November-December).


The first election under U. S. law.
Meeting of the Legislative Assembly.

The first election in the Island under the provisions of the


Act recited above occurred on the 6th of November
simultaneously with the elections in the United States. It
seems to have been almost entirely a one-sided vote. "About
two weeks before election day," says a despatch from San Juan,
November 7, "the Federal Party, which carried the island at
the election of less than a year ago by a majority of 6,500
votes, suddenly withdrew from the electoral contest. The
Federal leaders sent instruction to their followers not to
appear at the polls, but the Federal Election Judges were
instructed to appear and watch the proceedings until the
elections were concluded in order to gather evidence of any
unfairness in the registration and any irregularity in the
voting. The Federal Party intends to institute court
proceedings after the election in the hope of nullifying it,
claiming that gross irregularities in the registration and
voting will be shown, and alleging that the districting was
not done according to law." Only about 200 Federals voted, it
is stated, while some 60,000 votes were cast for the
candidates of the Republicans. Governor Allen cabled the
following announcement of the election to President McKinley:
"I am gratified and delighted. The outcome in Porto Rico is a
guarantee of the island's future. To bring people who had long
been under different rules and conditions to their first
general election, to have the election pass off as quietly and
orderly as in any State of the North conducted by the people
without let or hindrance, and without a soldier or armed force
of any sort, and to have nearly 60.000 men march to the polls
to deposit their first ballot for self-government in such a
manner, are good reasons for congratulation, not only to the
people of the island, but to the painstaking members of the
Administration, who had worked diligently and patiently to
this end. This overwhelming Republican victory also means
legislation for the good of the island in line with the
American Administration. It means stable government and the
protection of property interests, with which prospective
investors in Porto Rico are deeply concerned. It means
education, public works, and all the beneficent works which
follow legislation wisely and conscientiously undertaken. It
is an emphatic declaration of unqualified loyalty to the
United States."

The newly elected Legislative Assembly met and the House of


Delegates was organized December 3. A correspondent of the
"New York Tribune," writing a week later, said: "Already
nineteen bills have been introduced. To introduce nineteen
bills in six days after organizing, as well as forming the
regular committees, is not bad work when it is considered that
not one of the members had the slightest idea of parliamentary
procedure. During the session one of the members may be seen
making frequent trips to the Executive Mansion, where he
confers with Secretary Hunt in regard to some doubtful point.
It is said by some that in a short time the lower house will
be controlled entirely by the portfolio members of the
Council. It is known that the five Porto Rican members of the
Council, when considering the question of franchises, etc.,
often vote contrary to their own ideas in order that the
Council may continue harmonious. But it is not likely that the
heads of departments will be able to control the thirty-five
members of the House. The House, although regularly elected,
is not representative of the island; the Federals refraining
from voting kept over half the natives from the polls. The
Federal party, it is asserted, is made up of the richest and
best element of Porto Rico. The Republicans, though in power,
do not feel that they are able to run things alone, so the
majority is willing to be dictated to by the Council.
Nevertheless there is a certain element in the House which
will not be dictated to. So soon as any really important bill
comes up for debate it is predicted that the House will divide
against itself. And a little later, when the House passes some
pet bill and the Council rejects it, the House will probably
resign in a body. It is a natural trait of the people.'

After another fortnight had passed, the same correspondent


wrote very discouragingly of the disposition shown by a
majority of the members of the House of Delegates, and their
conduct of business, and stated: "The popular opinion among
the Americans, even among some of the higher officials, is
that if the House continues as it is Congress will abolish it
altogether, and govern the island through a Governor and
Cabinet. Such irregular procedure has been followed that it is
a question here whether any business has been legally done."

{419}

PORTO RICO: A. D. 1901 (January),


Close of the first session of the Legislative Assembly.

The first session of the first Legislative Assembly of the


island came to a close on the 31st of January, 1901, and the
following remarks on its work were made in a newspaper
despatch of that date from San Juan: "Over one hundred bills
have been introduced in the House of Delegates, and dozens
have been passed by both houses, and are awaiting the
Governor's approval. … Committees have a hard day's work if
they get together and agree to pass the bills on hand before
midnight to-night. Ever since the House of Delegates resumed
business after the new year, eight or nine members have been
continually absent. There are only thirty-five members
altogether, and the island is small, yet twenty-six has been
the average attendance. A full attendance for even one day is
not recorded. It was predicted that a number of the members
would resign; they did not. They simply remained away, like
truant schoolboys. A bill has been passed providing for the
education of certain young Porto Rican men and women in the
United States, about two hundred of them having petitioned the
House of Delegates to be sent north at the island's expense.
It is not known on what ground these petitions have been made.
The island expends about $400,000 yearly on education, and
excellent educational facilities are offered. But the people,
in a way, seem to discredit the value of the opportunities at
hand."

PORTO RICO: A. D. 1901 (April).


Distress of the workingmen of the Island.
Their appeal to the President of the United States.
The following petition, signed by 6,000 of the workingmen of
Porto Rico, was brought to the United States by a delegate
from the Federation of Labor in Porto Rico and presented to
President McKinley on the 15th of April:

"The undersigned, workers of Porto Rico, without distinction


of color, political or religious creed, have the honor to
bring to your attention the following facts: Misery, with all
its horrible consequences, is spreading in our homes with
wonderful rapidity. It has already reached such an extreme
that many workers are starving to death while others, that
have not the courage to see their mothers, wives, sisters and
children perish of hunger, commit suicide by drowning
themselves in the rivers or hanging themselves from branches
of trees. All this, honorable sir, is due to the scarcity of
work, which keeps us in enforced idleness, the mother of our
misery. Our beautiful estates are idle; our lands are not
being cultivated; our shops remain closed; and our Chambers do
absolutely nothing to prevent our misery on this once so rich
an island. The Government and municipality do not undertake
any public works to keep us out of idleness. The emigration of
workers, unknown in this island before, increases day by day,
in proportion as misery increases. Under these trying
conditions we are no longer a happy and contented people. We
therefore, beg of you, honorable sir, to interest yourself in
our cause, leading us, as the father of our country, in the
path that will bring us work, and with it the means of
subsistence. We want work; nothing but work. We want to earn
the means of subsistence by the sweat of our brows; and nobody
better than our Chief Magistrate can help us by lending ear to
our appeals. "

----------PORTO RICO: End--------

PORTUGAL: A. D. 1891-1900.
Delagoa Bay Arbitration.
See (in this volume)
DELAGOA BAY ARBITRATION.

PORTUGAL: A. D. 1898.
Alleged Treaty with Great Britain.

There is said to be knowledge in diplomatic circles of a


treaty between Great Britain and Portugal, concluded in 1898,
which has never been made public, but which is understood to
engage the former to assist the latter financially and to
protect the kingdom as against dangers both external and
internal. In return it is believed that England received the
right to embark and disembark troops, stores and ammunitions
at any point on Portuguese territory in Africa, to keep them
there, or to convey them across Portuguese territory to any
point she might see fit, irrespective as to whether she was at
war with any third Power. Circumstances have given some
support to this rumor, but it has no positive confirmation.

PORTUGAL: A. D. 1899.
Reciprocity Treaty with the United States.

See (in this volume)


UNITED STATES OF AMERICA: A. D. 1899-1901.

PORTUGAL: A. D. 1899 (May-July).


Representation in the Peace Conference at The Hague.

See (in this volume)


PEACE CONFERENCE.

PORTUGUESE EAST AFRICA: A. D. 1895-1896.


War with Gungunhana.

See (in this volume)


AFRICA: A. D. 1895-1896 (PORTUGUESE EAST AFRICA).
POSTAGE, British Imperial Penny.

See (in this volume)


ENGLAND: A. D. 1898 (DECEMBER).

POWERS, Concert of the.

See (in this volume)


CONCERT OF EUROPE.

POWERS, The four great.

See (in this volume)


NINETEENTH CENTURY: EXPANSION.

PRATT, Consul:
Interviews with Aguinaldo at Singapore.

See (in this volume)


UNITED STATES OF AMERICA:
A. D. 1898 (APRIL-MAY: PHILIPPINES).

"PREDOMINANT MEMBER," Remarks of Lord Rosebery on the.

See (in this volume)


ENGLAND: A. D. 1894-1895.

PREHISTORIC DISCOVERIES.

See (in this volume)


ARCHÆOLOGICAL RESEARCH.

PREMPEH, Overthrow of King.

See (in this volume)


ASHANTI.
PRESBYTERIAN CHURCHES: Union in Scotland.

See (in this volume)


SCOTLAND: A. D. 1900.

PRESS, The:
Relaxation of restrictions in Poland.

See (in this volume)


RUSSIA: A. D. 1897.

PRESS, The:
Prosecutions in Germany.

See (in this volume)


GERMANY: A. D. 1900 (OCTOBER 9).

PRETORIA: A. D. 1894.
Demonstration of British residents.

See (in this volume)


SOUTH AFRICA (THE TRANSVAAL): A. D. 1894.

PRETORIA: A. D. 1900.
Taken by the British forces.

See (in this volume)


SOUTH AFRICA (THE FIELD OF WAR):
A. D. 1900 (MAY-JUNE).

PRIMARY ELECTION LAW.

See (in this volume)


NEW YORK STATE: A. D. 1898.

PRINCE EDWARD'S ISLAND.


See (in this volume)
CANADA.

{420}

PRINCETON UNIVERSITY:
Celebration of 250th anniversary.
Assumption of new name.

See (in this volume)


EDUCATION (UNITED STATES): A. D. 1896.

PRINSLOO, Commandant: Surrender.

See (in this volume)


SOUTH AFRICA (THE FIELD OF WAR):
A. D. 1900 (JUNE-DECEMBER).

PROCTOR, Senator Redfield:


Account of the condition of the Cuban Reconcentrados.

See (in this volume)


CUBA: A. D. 1897-1898 (DECEMBER-MARCH).

PROGRESSISTS,
PROGRESSIVES.

See (in this volume)


AUSTRIA-HUNGARY: A. D. 1897;
JAPAN: A. D. 1890-1898, and after;
SOUTH AFRICA (CAPE COLONY): A. D. 1898,
and 1898 (MARCH-OCTOBER).

PROHIBITION PARTY, The.

See (in this volume)


UNITED STATES OF AMERICA:
A. D. 1896 (JUNE-NOVEMBER);
and 1900 (MAY-NOVEMBER).

PROHIBITION PLEBISCITE, Canadian.

See (in this volume)


CANADA: A. D. 1898 (SEPTEMBER).

PROTECTIVE TARIFFS.

See (in this volume)


TARIFF LEGISLATION.

PROTOCOL, for suspension of Spanish-American War.

See (in this volume)


UNITED STATES OF AMERICA:
A. D. 1898 (JULY-DECEMBER).

PRUSSIA: Census, 1895.

See (in this volume)


GERMANY: A. D. 1895 (JUNE-DECEMBER).

PRUSSIA: A. D. 1899-1901.
Canal projects.

See (in this volume)


GERMANY: A. D. 1899 (AUGUST); and 1901 (JANUARY).

PRUSSIA: A. D. 1901.
Bicentenary celebration.

The bicentenary of the coronation of the first King of Prussia


was celebrated with much ceremony and festivity on the 18th of
January, 1901.

You might also like