Professional Documents
Culture Documents
React and React Native Fifth Edition Mikhail Sakhniuk All Chapter
React and React Native Fifth Edition Mikhail Sakhniuk All Chapter
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
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.
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.
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:
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?
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:
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.
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.
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
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.
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:
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
cd my-react-app
1. Install dependencies:
npm install
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.
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:
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.
Hello JSX
Without further ado, here's your first JSX application:
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
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
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.
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.
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>© 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:
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.
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 />);
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>
);
}
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.
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:
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:
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.
IMPORTANT NOTE
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>
);
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.
IMPORTANT NOTE
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 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."
"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."
{418}
"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."
{419}
PORTUGAL: A. D. 1891-1900.
Delagoa Bay Arbitration.
See (in this volume)
DELAGOA BAY ARBITRATION.
PORTUGAL: A. D. 1898.
Alleged Treaty with Great Britain.
PORTUGAL: A. D. 1899.
Reciprocity Treaty with the United States.
PRATT, Consul:
Interviews with Aguinaldo at Singapore.
PREHISTORIC DISCOVERIES.
PRESS, The:
Relaxation of restrictions in Poland.
PRESS, The:
Prosecutions in Germany.
PRETORIA: A. D. 1894.
Demonstration of British residents.
PRETORIA: A. D. 1900.
Taken by the British forces.
{420}
PRINCETON UNIVERSITY:
Celebration of 250th anniversary.
Assumption of new name.
PROGRESSISTS,
PROGRESSIVES.
PROTECTIVE TARIFFS.
PRUSSIA: A. D. 1899-1901.
Canal projects.
PRUSSIA: A. D. 1901.
Bicentenary celebration.