Exercise 4 - Building A Rich UI Application by Using Reactand ES8
Exercise 4 - Building A Rich UI Application by Using Reactand ES8
2
Exercise 4. Building a rich front-end application by using React and ES8
EXempty
Overview
This exercise guides you through building an interactive and rich client-side application by using
React. You also explore the async/await feature of ECMAScript 2017, which is commonly known as
ES8, and some features of ES8 through a server-side application by using Node.js.
Objectives
By the end of this exercise, you should be able to accomplish these objectives:
• Deploy a React application on IBM Cloud.
• Deploy a Node.js application on IBM Cloud.
• Explore the structure of the React application.
• Explore the ES8 features of the Node.js application.
Prerequisites
Before you start, be sure that you meet these prerequisites:
• An IBM Cloud account.
• An understanding of Cloud DevOps basic concepts.
• An understanding of Git basic concepts.
• Access to a web browser: Google, Chrome, or Mozilla Firefox.
Introduction
In this exercise, you use two JavaScript frameworks, React and Express, to build the Tone Analyzer
sample application, which takes input from the user on the client side, sends it to the Tone Analyzer
service on the server side to be analyzed, and then sends the results in an HTTP response to be
displayed on the client side.
To avoid confusion between the client-side files and the server-side files, keep the client files in a
separate application from the server application.
EXempty
React is a JavaScript-based front-end web application framework that you use to develop
single-page applications. The single-page application is a web page that loads one HTML page and
dynamically updates it as the user interacts with the app.
Express is a web application framework for Node.js. It is designed for building full-stack web
applications and back-end only APIs.
ECMAScript/ES is a language specification that standardizes JavaScript. ECMAScript is used for
client-side scripting on the web and for writing server applications and services by using Node.js. In
this exercise, you use the async/await feature of ECMAScript 2017, which is commonly known as
ES8. ES8 improves the asynchronous programming experience by providing an async function
with an await fulfillment.
EXempty
Exercise instructions
In this exercise, you complete the following tasks:
__ 1. Create a Tone Analyzer service.
__ 2. Create a Node.js application.
__ 3. Integrate the Node.js application and Tone Analyzer service.
__ 4. Clone the React application and Node.js application from GitHub by using the Delivery
Pipeline.
__ 5. Integrate the React application and the Node.js application
__ 6. Explore the React application
__ 7. Explore the Node.js application code.
__ 8. Test your application.
__ 9. Clean up the environment.
__ 5. Create a Tone Analyzer service by keeping the default values, as shown in the following
figure.
EXempty
__ 6. Click Create.
EXempty
__ 5. Accept the default for region and pricing plan, as shown in the following figure.
__ 6. Select SDK for Node.js as runtime and enter the app name as app-express-XXX, where
XXX are three unique characters. Accept the rest of the default values, as shown in the
following figure.
EXempty
__ 7. Click Create.
__ 8. Wait until the status changes to This app is awake as shown in the following figure, then
click Visit App URL.
__ 9. A new tab opens as shown in the following figure. Copy the URL and paste it in a text editor
for later use. This is the URL to the Node.js server application.
EXempty
EXempty
EXempty
Note
In this example, the user’s region is London, so no Cloud Foundry apps are displayed if Dallas is
selected.
__ 6. Your Cloud Foundry apps are displayed when the correct region, Cloud Foundry org, and
space are selected, as shown in the following figure.
__ 7. Click your Cloud Foundry app to select it. The CONNECT button is activated, as shown in
the following figure. Click CONNECT.
EXempty
EXempty
__ 10. The Node.js app and the Tone Analyzer service are now connected, as shown in the
following figure.
Part 4: Cloning the React and Node.js applications from GitHub by using
the Delivery Pipeline
In this part, you clone the React application code and the server application code from GitHub and
deploy it to IBM Cloud.
To deploy quickly the application, complete the following sections.
EXempty
Information
This is the region where the toolchain for the React application will be created.
__ 4. At the Create API key window, click Create as shown in the following figure.
EXempty
__ 5. Verify that the region where your Cloud Foundry app was created in Part 2. Creating a
Node.js application is selected or select it now (London in this example), as shown in the
following figure. The Organization and Space are automatically populated.
Note
To find your Region, check where the organization is by completing the following steps:
• In a new tab, go to the IBM Cloud dashboard and click Manage.
EXempty
EXempty
• In the left pane, click Cloud Foundry orgs. The window that is shown in the following figure
opens.
EXempty
• Click the name of your org. You find your region and your space, as shown in the following
figure.
__ 6. Click Git Repos and Issue Tracking and enter or verify the following information, as shown
in the following figure:
- Source repository URL:
https://github.com/IBM-SkillsAcademy/Cloud-Application-Developer
- Repository type: Clone
EXempty
__ 7. Click Create.
__ 8. A window opens (see the following figure). Click Delivery Pipeline.
EXempty
__ 9. You are redirected to the Stages page to build and deploy your application, as shown in the
following figure. Click the Stage Configuration icon (the gear icon) in the Build Stage pane.
EXempty
Note
Do not worry about STAGE FAILED in the Deploy Stage pane because you are going to configure it
in the next steps.
The window that is shown in the following figure opens. Make sure that the Input tab is
selected.
EXempty
__ 11. Select the Jobs tab. The window that is shown in the following figure opens.
EXempty
__ 12. Select Custom Docker Image for Builder type. This selection opens another configuration
window. Enter the following information:
- Docker image name: node:latest
- Build Script:
#!/bin/bash
cd NodeApp/Ex4
cd client
npm install
npm run build
- Build archive directory:
NodeApp/Ex4/client/build
Your build configuration should look like the following figures.
EXempty
EXempty
Information
You need a custom Docker image to build this application and the latest Node version. It is a best
practice to have a newer version of Node.js to support ES8 if you are going to use it inside the
code.
You build the application by running npm run build, which builds the app for production and places
it in the build folder. It correctly bundles React in production mode and optimizes the build for the
best performance.
EXempty
Note
If you create a file that is named Staticfile in the root directory of your app, Cloud Foundry
automatically uses the Staticfile buildpack when you push your app.
The Staticfile file can be an empty file, or it can contain configuration settings for your app. In
this exercise, you leave it empty by using the command touch Staticfile.
EXempty
After both stages run, you see an output like the following figure.
EXempty
__ 2. Expand Coud Foundry Apps and open the details page for the Node.js application
(app-express-xxx) that you created in Part 2.
__ 3. Click Overview. The window that is shown in the following figure opens.
__ 4. Scroll down and click Enable in the “Continous delivery” pane. The window that is shown in
the following figure opens.
EXempty
__ 5. In the “Git Repos and Issue Tracking” pane, complete the following fields, as shown in the
following figure:
- Repository type: Clone
- Source repository URL:
https://github.com/IBM-SkillsAcademy/Cloud-Application-Developer.git
EXempty
Troubleshooting
If the default Repository Name is already in use as shown in the following figure, change the name
to make it unique.
EXempty
__ 8. In the Create API key window that opens, click Create, as shown in the following figure.
EXempty
You are redirected to the window that is shown in the following figure.
__ 10. Click Delivery Pipeline.You are redirected to the Build and Deploy Stage window, as shown
in the following figure.
EXempty
__ 11. In the Build Stage pane, click the Stage Configuration icon (the gear icon) and then select
Configure Stage, as shown in the following figures.
__ 12. Add the Build configuration options that will be used to build the Node.js application by
completing the following fields, as shown in the following figure:
- Builder type: Custom Docker Image
- Docker image name: node:latest
- Build script:
cd NodeApp/Ex4/server
npm install
- Build archive directory: NodeApp/Ex4/server
EXempty
Note
You need a custom docker image to build this application because you need the latest node version
(Node.js 7.6 is the official supported version for ES8).
EXempty
__ 15. The deployment script must look like the following code:
#!/bin/bash
cf push "${CF_APP}"
#view logs
#cf logs “${CF_APP}” --recent
EXempty
__ 2. Select the location that you wrote down in section Cloning the React application, step __ 2,
which is Frankfurt in this example, as shown in the following figure. This is the toolchain for
the React application.
EXempty
__ 4. The Git repo for the Cloud Application Developer course is displayed, as shown in the
following figure. The folder NodeApp contains the code for the Node.js exercises.
EXempty
EXempty
EXempty
Attention
When you add the baseUri, make sure that it does not include a slash “/” at the end. The format is
https://app-express-xxx.eu-gb.cf.appdomain.cloud.
__ 10. Scroll down and click Commit changes, as shown in the following figure.
__ 11. Go back to the Delivery Pipeline to monitor the progress of the deployment. You can access
your Toochains from your logged in IBM Cloud session at https://cloud.ibm.com/devops/.
Click Delivery Pipeline.
__ 12. Wait a few minutes until your application is deployed again. The results that are shown in
the following screen are displayed when the application completes deployment.
EXempty
Hint
You can continue with the next part while the application is being deployed.
EXempty
EXempty
You find two folders: client and server. The client folder contains the React application. To
explore the client folder, click client > src, as shown in the following figure.
EXempty
Information
The src folder contains JavaScript files and CSS files that you use in your application. Here are the
files:
• Index.js is the JavaScript entry point.
• The basic folder structure in any React project is as follows:
▪ package.json: This file contains the list of node dependencies that are needed.
▪ public/index.html: When the application starts, this file is the first page that is loaded. It is
the only .html file in the entire application because React is generally written in JavaScript
XML (JSX). Also, this file has the line of code <div id=”root”></div>, which is significant
because all the application components are loaded into this div.
▪ src/index.js: This is the JavaScript file that corresponds to index.html. This file has the
following significant line of code:
▪ ReactDOM.render(<App />, document.getElementById(‘root’));
▪ src/index.css: The CSS file that corresponds to index.js. It carries all the styles.
▪ src/App.js: This is the file for App Component, which is the main component in React that
acts as a container for all the other components.
EXempty
▪ src/App.css: This is the CSS file that corresponds to App Component, which carries all the
styles.
__ 4. Click App.js. This file is where you can create your components, as shown in the following
figure.
The previous figure shows what the top of the example App.js file looks like. When you create a
component in a React application, consider the following points:
• Import React and any stylesheets from react. Then, use the same syntax to import all your
individual components. In this exercise, you import the Result component that shows the results
of the Tone Analyzer.
• The component name is App, which is denoted by the file name that is shown in the following
statement:
export default class App extends Component {}
• The constructor is where you initialize a state. If you do not initialize a state and bind methods,
you do not need to implement a constructor for your React component. In this exercise, you
initialized the text and the tones, as shown in the following lines:
EXempty
constructor() {
super();
this.state = {
text: 'Four score and seven years ago our fathers brought forth on this
continent, a new nation, conceived in Liberty, and dedicated to the proposition
that all men are created equal. Now we are engaged in a great civil war, testing
whether that nation...',
tones: []
};
}
• The componentDidMount() method is a lifecycle method that runs after the component output
is rendered to the Document Object Model (DOM). It is run immediately after a component is
mounted (inserted into the tree). Initialization that requires DOM nodes should go into this
method. If you need to load data from a remote endpoint, this method is a good place to
instantiate the network request. In this app.js file, this method is used to fetch the text that is
written and call the getTones() function, as shown in the following lines:
componentDidMount() {
document.body.style.background = '#cafafe';
document.getElementById('text-input').value = this.state.text;
this.getTones();
}
• The getTones() function is an async function that sends the text to the Node.js application and
waits for a response before the function sets the state (setState) of the tones. The function
applies the async and await properties in ES8 so that the function can be called
asynchronously, but it waits until it receives a response before it runs. The following lines show
how the function is implemented:
async getTones() {
try {
const response = await
fetch(`${this.baseUri}/tone?text=${this.state.text}`);
const toneResponse = await response.json();
this.setState({
tones: toneResponse.document_tone.tones
});
} catch (error) {
this.setState({
tones: []
});
}
}
EXempty
• After the previous lines, you have the render() and return functions. The return value of this
function is shown on the screen. Whenever the render() function is called, the screen is
rerendered automatically by the application.
render() {
return (
<div className="container">
<h1>Tone Analyser</h1>
<div>
<div className="form-group">
<textarea className="form-control" id="text-input"
placeholder="Enter text here" onChange={e=>this.updateText(e)}></textarea>
</div>
<button className="btn btn-info" onClick={() =>
this.getTones()}>Retrieve Tones</button>
</div>
<Result text={this.state.text} tones={this.state.tones}/>
</div>
);
}
}
• The state feature is a private feature that belongs only to a single component. The state
feature enables React components to change dynamically output over time in response to
certain events. For example, {this.state.text} can be changed later by using the
setState() function as follows:
this.setState({
tones: toneResponse.document_tone.tones
;
EXempty
__ 2. Click Toolchains.
__ 3. Choose the Location where you created your toolchain for the Node.js application in section
Cloning the Node.js Server application, step __ 5. In this example the location is London.
__ 4. Click the Eclipse Orion Web IDE icon under Tool Integrations.
EXempty
__ 6. Click NodeApp > Ex4 > server, and then select server.js to open the entry point of the
server application, as shown in the following figure.
EXempty
By using server.js, whenever the React application needs a result from Tone Analyzer, the server
sends a GET HTTP request to the Node.js application when the Node.js application is running. The
Node.js application sends the data to the Tone Analyzer service and returns the result in the HTTP
response.
In this code, you find some of the ECMAScript features:
• The const and let keywords
const port = process.env.PORT || 5001;
let parameters = {
tone_input: { 'text': req.query.text },
content_type: 'application/json'
};
In ECMAScript 2015 (ES6), the two keywords let and const were added. The difference
between const and let is that const is a signal that the identifier will not be reassigned. let is
a signal that the variable might be reassigned, such as a counter in a loop or a value swap in an
algorithm. let also signals that the variable is used only in the block in which it is defined, which
is not always the entire containing function.
• The async/await function
In ECMAScript 2017 (ES8), the async/await feature was added. The async function declaration
defines an asynchronous function, which returns an Async Function object.
An async function can contain an await expression, which pauses the execution of the async
function and waits for the passed Promise's resolution and then resumes the async function's
execution and returns the resolved value, as shown in this code snippet:
app.get('/tone', async (req, res) => {
let parameters = {
tone_input: { 'text': req.query.text },
content_type: 'application/json'
};
try {
const toneAnalysis = await toneAnalyzer.tone(parameters);
res.send(toneAnalysis);
} catch (error) {
console.log(error);
res.status(error.code).send(error);
}
;
EXempty
__ 3. Your front-end application opens in another browser tab as shown in the following figure.
EXempty
__ 4. Enter text into the Tone Analyzer text box and click Retrieve Tones, as shown in the
following figure.
EXempty
EXempty
EXempty
EXempty
__ 3. Type the toolchain name to confirm deletion and click Delete, as shown in the following
figure.
__ 6. Type the toolchain name to confirm deletion and click Delete, as shown in the following
figure.
EXempty
__ 3. Click Actions (the three dots icon) for your React application and select Delete, as shown
in the following figure.
EXempty
__ 4. Select the routes to delete and click Delete, as shown in the following figure.
EXempty
EXempty
__ 8. Click Delete.
EXempty
__ 3. At the Delete resource window, click Delete.
EXempty
Exercise review and wrap-up
During this exercise, you achieved the following goals:
• Learned the basics of the React framework when you explored a basic React application that
uses React components to interact with the user.
• Learned the basics of ES8 when you explored some features of ES8 in the Node.js application.
• Learned how to serve static files to serve the front-end files and deploy a React application.
• Used Git to clone an existing project. You used Git to clone the source code from GitHub and
used it as the basis for this exercise.
References
https://reactjs.org/docs/getting-started.html
https://www.ecma-international.org/publications/standards/Ecma-262.htm
Troubleshooting
The following path contains all the code for this exercise:
https://github.com/IBM-SkillsAcademy/Cloud-Application-Developer/tree/master/NodeApp/Ex4