Professional Documents
Culture Documents
This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.
The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
This chapter serves as our starting point for learning how to create
components using the JavaScript library React.
React is an open source library used to create interactive user
interfaces for web applications. By using React, you can build reusable
components to construct rich and scalable user interfaces.
In this chapter, you will learn the basics of creating React components
and build your first component. We will also review the fundamental
principles of JSX, a syntax used to create React elements, and how to
integrate it into our code.
You will develop a solid understanding of React’s foundational
principles by creating simple components, ready to be integrated into
larger projects. This hands-on approach will allow you to absorb the
essential basics of React while preparing you to collaborate on more
extensive projects.
Ready to get started? Let’s go!
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Counter: {count}</h2>
<button onClick=
{handleIncrement}>Increment</button>
</div>
);
};
Now, let’s assume the user clicks the Increment button multiple times.
With each click, React updates the counter’s state and triggers a
reconciliation process to update the user interface.
Here’s what happens during reconciliation:
1. The user clicks the button, triggering the handleIncrement() function.
3. React compares the virtual tree representing the current state of the
user interface with the previous version.
5. React updates only the parts that have changed in the actual DOM,
rather than re-rendering the entire element tree.
<div>
<h2> Counter: 0</h2>
<button>Increment</button>
</div>
<div>
<h2> Counter: 1</h2>
<button>Increment</button>
</div>
In this example, React notices that only the counter value has changed
(0 became 1). It will update the relevant part of the DOM to reflect this
change without touching other parts of the DOM.
This is how React optimizes performance by using reconciliation to
update only the parts of the user interface that have actually changed,
minimizing the number of expensive DOM manipulation operations.
Decomposing an Application into Components
Decomposing an application into components, as suggested by React, is a
common practice in software development. This allows for creating a
modular structure that facilitates code maintenance, reusability, and
understanding.
Here’s a simple example of decomposing an application into
components:
Let’s say we want to build an application that displays a list of tasks to
do, each with a check box to indicate whether the task is completed or
not.
The first step would be to divide the application into two main
components: a parent component TaskList and a child component
TaskItem.
The parent component TaskList would be responsible for managing
the complete list of tasks to do. It would handle retrieving the list data
from a data source (e.g., an API or a database), sorting, filtering, and
passing them down to the child component TaskItem (see Figure 1-1).
Then, at the end of the creation of the reactapp application, you will get
the screen shown in Figure 1-6.
Figure 1-6 Completion of React application creation
Once the application is created, simply enter the suggested commands
in the command prompt: these commands are “cd reactapp”, followed by
“npm start”.
The “npm start” command starts an HTTP server based on Node.js,
which will allow you to view your React application in a web browser. The
server that’s started listens for connections on port 3000, as indicated in
the command prompt window in Figure 1-7.
Figure 1-7 Starting the server containing the React application
Now, let’s establish a connection with the server by using the URL
http://localhost:3000 as shown in the window in Figure 1-8. Type this
URL into your web browser.
Figure 1-8 Display of the URL http://localhost:3000
In the web browser, you will see the “reactapp” application that we
created using the “create-react-app” command.
The “reactapp” application is built with React and is located in the
“reactapp” directory. Now, let’s explore the files and directories within the
application directory.
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Let’s describe the code written in the previous index.js file. We start
by importing the core React modules, namely, React and ReactDOM, into
the index.js file using JavaScript’s import statements.
The import statement in JavaScript is used to import one or more
functionalities from a directory or file where they are defined. Once these
functionalities are imported, they become accessible within the module
that imports them.
The React and ReactDOM modules are located in the node_modules
directory, which is automatically created when the “reactapp” application
is generated using the create-react-app command:
The React module contains the code of the React library.
The ReactDOM module is specialized for using React in HTML pages
(React can also be used in native mobile applications under the name
React Native).
Next, we import the App component from the App.js file using the
import statement: “import App from ‘./App’”. We can see the usage of the
App component in the parameter of the root.render() method. The
root.render() method is used to indicate the HTML code that will be
inserted into the HTML element with the id “root”.
The App component is written here in the form <App />, which is the
syntax used for writing components with React. This writing style is
called JSX and is similar to XML. Notice that we write JSX code without
surrounding it with quotes (we write <App /> instead of “<App />”),
because what we are writing here is not a string but represents JSX code,
which is then transformed into HTML code during the execution of the
React program.
The <React.StrictMode> element included in the JSX code of the
index.js file allows displaying additional information in the JavaScript
console in case of errors. You can find more information at
https://react.dev/reference/react/StrictMode.
The JavaScript console is typically displayed by pressing the F12 key
on the keyboard.
The element with the id “root” is obtained with the instruction root =
ReactDOM.createRoot(document.getElementById(‘root’)). If you view the
contents of the index.html file located in the public directory, you will see
that the only HTML code in the index.html page corresponds to a <div>
element with the id “root” (written as <div id=“root”></div>). It is within
this <div> element that the HTML code created during the root.render()
method call will be inserted.
Let’s take a look at the contents of the index.html file.
Step 2: Contents of the index.html File
Here is the content of the index.html file in the public directory of the
application, where we have highlighted the <div> element:
File: public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico"
/>
<meta name="viewport" content="width=device-
width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-
app"
/>
<link rel="apple-touch-icon"
href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your
web app is installed on a user’s mobile device or
desktop. See
https://developers.google.com/web/fundamentals/web-
app-manifest/
-->
<link rel="manifest"
href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags
above.
It will be replaced with the URL of the
`public` folder during the build.
Only files inside the `public` folder can be
referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico",
"%PUBLIC_URL%/favicon.ico" will work correctly both
with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL
by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run
this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you
will see an empty page.
function App() {
return (
<Counter />
);
}
function Counter() {
var count = 0;
return (
<>
The counter is set to: {count}
</>
)
}
body {
margin:10px;
}
Let’s select the Components tab from the list. A description of the React
components used in the application will appear. The component
hierarchy of App and Counter can be found there. This will be particularly
useful during application debugging (see Figure 1-11).
Figure 1-11 Display of components in React DevTools
function Counter() {
var count = 0;
setInterval(function() {
count++;
console.log("count =", count);
}, 1000);
return (
<>
</>
)
}
Let’s run this program in the browser, displaying the console window
to view the value of the counter. This counter value is also displayed on
the HTML page using the expression {count} (see Figure 1-12).
Figure 1-12 Incrementing the counter
Each line is displayed twice in the console, hence the number 2 displayed
on the right for each line in the console. This is due to the use of React’s
strict mode, using the <React.StrictMode> tag in the index.js file. To stop
using this strict mode, simply remove the <React.StrictMode> tag
surrounding the <App/> tag in the index.js file.
We remove the <React.StrictMode> tag in the index.js file, which
becomes as follows:
File src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
function Counter() {
const [count, setCount] = useState(0);
setInterval(function() {
setCount(count+1);
console.log("count =", count);
}, 1000);
return (
<>
The counter is set to: {count}
</>
)
}
1898.
Valkamalle.
1896.
Elämä ja ihanteet.
1898.
Täyteläs rinta.
1896.
Nuoret, nuoret!
1896.
Konsahan!
Konsahan koittaa
Suomelle raitis ja puhtonen aamu,
väistyvi väikkyen yöhyen haamu!
Konsahan koittaa
kaikille kansani lapsille päivä,
haihtuvi huolien häilyvä häivä!
Konsahan voittaa
kansani kaipaava, etsivä henki
kaivatun lämmön ja kirkkaudenkin!
Konsahan voittaa!
1896.
Keväiset yöt.
1896.
1890.
Kultani kartano.
1899.
Pihlajan juurella.
1899.
Hänen luonansa.
1899.
1899.
Lemmenpaula.
Kuulepas sinä kullankukka, ruskotukka, sinisukka, kuulepas
kun sulle laulan mitä olen aatellut.
1899.
1898.
1899.
Sydämillä leikkimistä.
Sydämetön olen ma, moiti taikka vaikerra. Katsoin sinun
silmiisi, sinne hukkui syömeni.
1898.
Minä ja hän.
1898.
Juhannus ja joulu.
1899.
Taivaan pilvet.
1899.
1899.
1899.
3899.
Kukkaset ja kukkasvarkaat.
1899.
Jänis ja — kultani.
Niin täytyy.
1899.
Kullan haudalla.
1899.
Surujeni lampi.
1899.
1899.
Luottava vuottaja.
1899.
1896.
Raitis Rautiainen.
1899.
Päiväläispojan mietteitä.
Elämänlanka kukkia kasvaa ruusunpunaisia. Lempi on
nuorissa leimahdellut vuosia tuhansia.
1899.
Kulkijapoika.
Vaasassa 1898.
Hulivilipoika.
1899.
Vaikeassa asemassa.