Get up to 60 % extra points for free! More info
Only this week sale up to 80 % on e-learning courses of Java
discount week 60 - halloween

Lesson 2 - First application in React New

In the last lesson, Introduction to React, we introduced the React library and described its basic features.

In today's tutorial, we will show you how to create the first simple application, in which we will explain in more detail the basics of creating applications using the React library.

Application selection

Choosing a project on which we could demonstrate everything we needed was not entirely easy, but in the end, the winner was a simple calculator, the screenshot of which you can see below. So once we know what and what we're going to do, let's get to work! :)

Project creation

Last time we showed the complete basis for creating a React application. For today's project, however, we will use a slightly more advanced procedure, the output of which is also applicable to the production environment, ie the real deployment of the application on the Internet. We will use Node.js, mentioned in the last lesson, for this procedure. It's relatively simple. All you have to do is have it installed and use it to run a single command in the folder where you want to place the project. The parameter is the name of the project:

npx create-react-app calculator

That is all. Now wait for the installation to complete, simply open the project in your chosen IDE or text editor and we can start programming.

Launch the application

It would be good to try how to run the application now. What we have installed is the complete basis of the React application powered by a local server with support for continuous JSX translation, which, among other things, offers us the opportunity to compile the final version of the application for a production environment. To start, just enter the command again inside the project folder:

npm start

So it starts our application within the local server by default at the address http://localhost:3000/ and immediately opens it in the default browser. The result immediately after installation should look something like this:

React App
localhost:3000

In addition, the server monitors changes to the application files during its run and automatically reloads the application if something changes. So all we need to do is edit the code and we instantly see the results of our changes directly in the browser.

Project structure

Furthermore, it would not be wrong to describe the new structure of the project, which we will work with:

  • node_modules/ - Installed tools for our application, which stores npx (Node.js).
  • public/ - Folder for placing publicly available resources such as index.html and also eg images, etc. index.html - The main input file to our web application. It contains the basis of the structure of our HTML.
  • index.html - The main input file to our web application. It contains the basis of the structure of our HTML.
  • src/ - Source codes of our application. Here we will mainly program! App.css - For simplicity, we will place all CSS styles of our application here.

    App.js - Definition of the main React component of our application. We will work with her in a moment.

    index.js - A file that loads the React component of our application into the HTML structure.

    ... - Other files that are not important to us at the moment, which can also be deleted.

  • App.css - For simplicity, we will place all CSS styles of our application here.
  • App.js - Definition of the main React component of our application. We will work with her in a moment.
  • index.js - A file that loads the React component of our application into the HTML structure.
  • ... - Other files that are not important to us at the moment, which can also be deleted.
  • ... - Project configuration files created with npx. For now, we will be content with the default settings of the project.

Project editing

And now let's finally embark on editing the source code!

Public / index.html

Let's start logically with the main HTML framework of our application:

<!DOCTYPE html>
<html lang="cs">

<head>
    <!-- Introductory information for the browser. -->
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />

    <!-- Description and title of the application. -->
    <meta name="description" content="Simple calculator in using React library from ITnetwork.cz">
    <title>React calculator | ITnetwork.cz</title>

    <!-- React icon. -->
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
</head>

<body>
    <noscript>You must enable JavaScript to run this application.</noscript>

    <!-- The root of our component structure of the application. -->
    <div id="root"></div>
</body>

</html>

You can see that this is the standard structure of an HTML page with an entry point into our component structure.

What is worth mentioning is a %PUBLIC_URL% in the form of %PUBLIC_URL%, which always correctly fills out %PUBLIC_URL% path to our folder public/ ;)

Src / index.js

What we are missing now compared to the past is the code for rendering the application component into our HTML structure, which was simply moved to a separate file:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

// Rendering an instance of an application component into an HTML structure.
ReactDOM.render(<App />, document.getElementById('root'));

As you can see, in terms of functionality, this is nothing we don't already know. It is worth noting, however, the use of JS import from ES6 +, thanks to which we can compose the files of our application in a much more convenient and clear way. So you can forget about inserting many <script> tags into the HTML structure because this way you simply insert what you need right where you need it :)

Components

When working with the React library, our main focus is to create the user interface (UI) of the application. Therefore, before starting work, it is not necessary to first think about its structure, than to divide it into React components, and finally add the required functionality to them by manipulating their properties and state. So what will the structure of our application look like?

Structure

As you can see in the picture above, the layout of our calculator is relatively simple. Its HTML structure might look something like this:

<form>
    <label for="x">
        First issue: <input id="x" type="number" name="x" required value="0" />
    </label>
    <label for="y">
        Second number: <input id="y" type="number" name="y" required value="0" />
    </label>
    <label for="operation">
        Operation:
        <select id="operation" name="operation" required value="">
            <option value="">--Select an operation--</option>
            <option value="add">Addition</option>
            ...
        </select>
    </label>
    <input type="submit" value="Count" />
</form>
<div>
The result is: 10</div>

Well, now it's time to split this structure into React components and then reassemble it.

I would see it as a fine demonstration of the use of the React library for a quality demonstration. So one component for numeric inputs and another for operation selection. We then compose them into a calculator form component. Finally, we insert the form together with the component for the result into the component of our application. It sounds good, so let's start with the little ones and gradually put them together.

For these new components of ours, we will create the src/calculator/ folder for the sake of clarity.

Src / calculator / NumberInput.js

Let's start with the numeric input component:

import React, { Component } from 'react';

export default class NumberInput extends Component {
    render() {
        return (
            <label htmlFor="x">
                First issue:
                <input id="x" type="number" name="x" required value="0" />
            </label>
        );
    }
}

As you can see, the definition using the JS class is the same as in the last lesson, and thanks to the use of JSX, we can insert our HTML code directly here.

The smarter of you have probably noticed that there is one change. Instead of the HTML for attribute, htmlFor used for <label>. This is because when we mix HTML directly into JS, we must not forget that for is a reserved keyword for the cycle in JS. JSX, therefore, introduces a replacement instead, which translates into the resulting HTML correctly as a for.

Src / calculator / OperationSelect.js

We will continue in the same spirit with the operation selection component:

import React, { Component } from 'react';

export default class OperationSelect extends Component {
    render() {
        return (
            <label htmlFor="operation">
                Operation:
                <select id="operation" name="operation" required value="">
                    <option value="">--Select an operation--</option>
                    <option value="add">Addition</option>
                    ...
                </select>
            </label>
        );
    }
}

Src / calculator / Result.js

Next, we will look at the component for the result:

import React, { Component } from 'react';

export default class Result extends Component {
    render() {
        return <div className="Result">The result is: 10</div>;
    }
}

Since we will also want to apply CSS to the result, we will mark it using the HTML attribute class. However, again this is a JS reserved word, so we will use className instead in JSX. It is also used in connection with the designation of the components themselves, so for the sake of clarity, we will choose the same name as my component.

Src / calculator / CalculatorForm.js

Now that we have the relevant parts, we can put together a component of our form:

import React, { Component } from 'react';
import NumberInput from './NumberInput';
import OperationSelect from './OperationSelect';

export default class CalculatorForm extends Component {
    render() {
        return (
            <form className="CalculatorForm">
                <NumberInput />
                <NumberInput />
                <OperationSelect />
                <input type="submit" value="Count" />
            </form>
        );
    }
}

Here we see a beautiful and simple composition of components. It is true that we have twice the same numbered numeric input, but of course, we will correct that :)

Src / App.js

Finally, we look at the component of our application itself, which we modify as follows:

import React, { Component } from 'react';
import CalculatorForm from './calculator/CalculatorForm';
import Result from './calculator/Result';
import './App.css';

export default class App extends Component {
    render() {
        const title = 'React calculator';

        return (
            <div className="App">
                <h1>{title}</h1>
                <CalculatorForm />
                <Result />
            </div>
        );
    }
}

Again, nothing complicated, I just allowed myself a demonstration of inserting the value of a variable from JS into JSX. You can see that this is done using the {} syntax {} and it's very straightforward again.

You may also notice that CSS for our application can also be inserted directly using JS import.

And that's all. When you start the application now, you should see the stacked corresponding HTML structure in the browser.

Next, in Lesson React calculator components, we'll look at the properties and states of our calculator components.


 

Did you have a problem with anything? The source code of the sample application can be downloaded every few lessons. In the meantime, go ahead and then compare your application with the pattern and easily fix it.

Previous article
Introduction to React
All articles in this section
React Basics
Article has been written for you by Vlasta Řenčová
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
Passionate reader, student, coder and writer.
Activities

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!