React is a javascript front-end library that is used for building user interfaces. React has gained a wide popularity among web and mobile apps developers for its design, simplicity, and efficiency. In React, you build application user interfaces by creating pieces of the UI code as separate objects called components. When the application is launched, React builds the user interface by assembling the individual components to generate the complete view that we see in the browser or mobile device.
In this post, we will take an introductory approach to understanding the very basics of React application development.
Although React applications are mostly developed with build tools, this part of the introductory discussions on React basics will adopt the classic way of loading script libraries. In a separate part, we will look at how we can develop React applications by building with node packages such as webpack, babel, and React library packages.
While you can also use React for mobile applications development, we will only concentrate on developing user interfaces for web applications. After going through the discussions in this post, it is expected that you will have a broader understanding of the foundation of React for web applications development.
Welcome to React basics.
Prerequisites
In order to follow along and understand what is covered in this post, I will assume that you already have basic knowledge of web applications development. Specifically, I assume the you have basic knowledge of HTML, CSS, and javascript programming language.
I don’t actually expect that you have advanced knowledge in web development. If you are able to satisfy the above basic requirements, then you will be able to follow along. Let’s get started into the world of React development.
Table of Contents
- Application Project
- Static HTML Elements
- Dynamic HTML Elements
- Dynamic Elements with Native Javascript
- Dynamic Elements with React
- React JSX
- Transpiling with Babel
- React Components
- Summary
Application Project
To begin, we will create a minimal application that consists of single html and javascript files. We will build on the content of these files as we go through the discussion in this post.
Create a folder in your desired location and give it a name of your choosing. In my case, I will name the folder react-intro-1 in my root directory. That is, C:\react-intro-1. The folder you create will be the directory in which we will organise our application files. You can use any text editor to create and organise your application files. In this post, I will be using Visual Studio Code.
If you are using VS Code, open the directory that you created. You can simply do this by clicking on the File menu, then on Open Folder from the drop down menu items. Now browse to select the folder that you created. Visual Studio Code will open with the directory you created as the root directory of the application files.
Initialise Application Project
Before we start coding, we should initialise our application project. Open a command prompt window and navigate to the application directory. If you are using VS Code, you can click on the Terminal menu to open a command prompt. We can now initialise our application by typing and executing the following command:
npm init -y
This will initialize our application and create a package.json file. The package.json file will contain all references to packages that our application will depend on. The truth is that we do not need npm
in this part of the discussion. However, we are applying the procedure here to prepare us for the next part in which it will be needed when we need dependency packages.
Organise Source Files
It is always a good idea to organise application files. This makes it easy to locate certain application resources that have been added to the project. In small projects, like what we will be doing in this post, the benefit of organising application source files may not be apparent. In large projects, however, the benefit of organising application source files will be clear. Nonetheless, we will organise our source files, albeit being a small application project. We will put our source files in a defined directory. We can name this directory src.
Create a folder in the root of our project and name it src. Within this directory, we will create two files: one html document file and one javascript file.
In the src directory, create a new file and name it index.html. Again, create another file in the same directory and name it index.js. Our application directory structure should look like what is shown in the following image:
Static HTML Elements
To better appreciate how React works, and to even understand it better, we will begin with a simple HTML document which contains static elements. By this, I mean that we will define the HTML elements that describe the user interface of our web page directly in the HTML document. For many years, this was the standard way of building web application interfaces, leaving the dynamic part of the application to be handled by javascript.
Click on index.html file, then type or paste the following HTML code in the file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Introduction to React: Part 1</title>
</head>
<body>
<div id="container">
<h1>Introduction to React</h1>
<p>React is a front-end javascript library used to build user interfaces.</p>
</div>
<script type='text/javascript' src='./index.js'></script>
</body>
</html>
You should be familiar with the content of this html document. When the above html document is loaded and rendered in a browser, you will see a page similar to the following:
We can see the heading and paragraph text that we typed in the html document rendered in the browser. Note that we typed the heading and the paragraph text directly in the html document. If we like, we can decide not to type these in the html document but rather create the html elements when the browser has already rendered the document on the page. In this case, we will be rendering html elements on the web page dynamically.
Dynamic HTML Elements
In the previous discussion, we typed the html elements which produced the content of our web page directly in the html document. This was before the browser rendered them on the page. These html elements were <h1></h1>
and <p></p>
. Specifically, we rendered the following html elements:
<h1>Introduction to React</h1>
<p>React is a front-end javascript library used to build user interfaces.</p>
There is another way we can achieve same. This is to dynamically create the html elements and then insert them on the page through the browser DOM. With this approach, we will not type the <h1></1>
and <p></p>
elements directly in the html document.
We will use two approaches to dynamically create and insert html elements on the web page. Firstly, we will see how this is done using native javascript. The second approach is to see how this is done using React. After going through these, you will appreciate and understand the philosophy of React.
From index.html file, clear <h1></h1>
and <p></p>
elements which produced the text rendered on the page. Our index.html file should now be as shown below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Introduction to React: Part 1</title>
</head>
<body>
<div id="container"></div>
<script type='text/javascript' src='./index.js'></script>
</body>
</html>
As can be seen, there is nothing contained in the div
with "id=container"
. We will dynamically create the h1
and p
elements and insert them within this container div
.
Dynamic Elements with Native Javascript
We can use native javascript to manipulate the web page with the Document Object Model (DOM). The DOM is a programming API which javascript uses to access and manipulate a web page when the application is running. Let’s see how we can do this.
Creating DOM Elements
Click on index.js file, then type or paste the following code which creates the heading:
// create the heading (h1) element
const heading = document.createElement('h1');
heading.innerText = 'Introduction to React';
As can be seen, we create elements in javascript using createElement()
method of the document
object. We have also set the text of the element that we created with innertText
. If we were to set the content of the element to another html element, we would set it with innerHTML
instead. Since we are setting the element value to a string
, we rather set the element value to innerText
property.
What we have done is that we have only created the h1
element with javascript. This will not automatically render the element on the page. If you refresh the document page in your browser, you will not see the heading text. To make the heading visible on the page, we will need to know which existing element in the document file or on the page will be the parent or container.
Rendering DOM Elements
Remember, we intend to insert the heading in the div
with id="container"
. We will need to get this div
element, then append the element that we created as a child.
Add the following code below the DOM element that we created.
// get the parent element (div)
const container = document.getElementById('container');
Your index.js file should now read as follows:
// create the heading (h1) element
const heading = document.createElement('h1');
heading.innerText = 'Introduction to React';
// get the parent element (div)
const container = document.getElementById('container');
Now that we have a reference to the container div
element, we can append the heading
element as a child with appendChild()
method. An alternative method that can be used is to call append()
. You can read on the difference between append and appendChild for more information.
// create the heading (h1) element
const heading = document.createElement('h1');
heading.innerText = 'Introduction to React';
// get the parent element (div)
const container = document.getElementById('container');
// Append the heading element to the container div
container.appendChild(heading);
If you refresh the document page in your browser, you will see the heading text rendered on the page. You can see this below:
Do you remember that in the static version, we typed everything directly in our index.html file? That included a paragraph of text. Let’s quickly create the p
element dynamically as well and see.
Maintain the content of index.js, then add the following code at the bottom:
// create the paragraph (p) element and set its text
const paragraph = document.createElement('p');
paragraph.innerText = 'React is a front-end javascript library used to build user interfaces.';
// append the paragraph as a child to the container div
container.appendChild(paragraph);
The content of index.js file should now read as follows:
// create the heading (h1) element
const heading = document.createElement('h1');
heading.innerText = 'Introduction to React';
// get the parent element (div)
const container = document.getElementById('container');
// Append the heading element to the container div
container.appendChild(heading);
// create the paragraph (p) element and set its text
const paragraph = document.createElement('p');
paragraph.innerText = 'React is a front-end javascript library used to build user interfaces.';
// append the paragraph as a child to the container div
container.appendChild(paragraph);
Save index.js file, then refresh your document page in the browser. You should now see the paragraph text also rendered on the page. This is the same content we saw when we initially typed everything directly in index.html file.
What we have achieved is that we have used native javascript to dynamically create html elements that describe the content of our page. We did not type the elements directly in the html document file. React uses similar methodology and extends this idea. As you may know already, React is based on javascript.
If you have understood our discussion to this point, then you will easily grasp the foundation of React. Let’s see how we can dynamically create our page view (user interface) using React and get the same rendered view.
Dynamic Elements With React
In the previous section, we saw how we can use native javascript to dynamically create and insert elements into the browser DOM. In this section, we will be using React library rather than native javascript to accomplish the same task. Since we will be using React for the remaining discussions, we will need to include its required library scripts.
Loading React Scripts
Rather than download React javascript files locally, let’s use CDN version of the library for the remaining discussions. Navigate to React CDN scripts page, then copy the two script tags for react development. This is shown below:
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
Your version of React may be different if the library has had an update after this post was published. However, that should not be a deterrent.
Once you copy, click on index.html file, then paste just above where we included the script tag for our index.js file. Your index.html file should now read as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Introduction to React: Part 1</title>
</head>
<body>
<div id="container"></div>
<!-- include script files for react (react and react-dom) -->
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<!-- include our script file -->
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
You can see from lines 12
and 13
that we are using two react files in our project file. Observe carefully: one file is react.development.js
whiles the other is react-dom.development.js
.
react.development.js
is the main library for developing React applications, and react-dom.development.js
contains utility for rendering react application in the browser DOM. The development
part of the name indicates that these files are preferred to be used at the development stage of our application. There is also react.production.min.js
and react-dom.production.min.j
s which can be used for live applications.
Creating Elements with React
Recall our discussion on creating DOM elements with native javascript. What we do is to call createElement()
on the document
object, while specifying the element we want to create. After creating the element, we set its content to innerText
or innerHTML
property, depending on whether the element content we want to set is a string
or Element
. For example:
const heading = document.createElement('h1');
heading.innerText = 'Introduction to React';
React has a similar way of creating an element and setting its content. This is done by similarly calling a createElement()
method on React
:
// create a react element (h1)
const heading = React.createElement('h1', null, 'Introduction to React');
The second argument to React’s createElement()
should be an object that defines the properties of the element being created. In this introductrory text, we will just set it to null
.
The third argument to createElement()
is optional and defines the content we want to set to the element. In React, this is considered as children of the element we want to create. The children can be text string
, array
, object
, or simply other ReactElement
. In this example, we are setting children, which we simply consider as element content in our example, to a text string
.
Rendering React Elements
Recall when we were rendering DOM elements with native javascript. To render a DOM element, we need to know which existing element in the html document file will be the parent. We obtained a reference to the parent element using its id
. When rendering elements with React, we go by the same approach. React needs to know which element in the html document file will be the parent to the ReactElement
s that have been created.
// get reference to the container element
const container = document.getElementById('container');
Once we have obtained a reference to the parent element, we render the children elements with the render()
method.
const heading = React.createElement('h1', null, 'Introduction to React');
// get the container div element
const container = document.getElementById('container');
// create the react object for the root container and use to render the element
ReactDOM.createRoot(container).render(heading);
On line 7
, we call ReactDOM.createRoot()
method and pass the container element as the root of all elements of the application UI, then we call to render()
method with the heading
element. In fact, it is possible for the element passed to the render()
method to contain child elements as well, like a div
containing child elements.
When the previous code is rendered, you should see the h1
element with the text Introduction to React
as we saw in rendering with native javascript.
Let’s even go further to see how we can include the paragraph of text. See it below:
// create the heading and paragraph elements
const heading = React.createElement('h1', null, 'Introduction to React');
const paragraph = React.createElement('p', null, 'React is a front-end javascript library used in building user interfaces.');
// create the Fragment element that will wrap the heading and paragraph elements
const fragment = React.createElement(React.Fragment, null, heading, paragraph);
// get the container div element
const container = document.getElementById('container');
// create root object for container and render the fragment
ReactDOM.createRoot(container).render(fragment);
On lines 2
and 3
, we separately create React elements for the heading
and paragraph
. On line 6
, we create a React Fragment
object that will wrap the heading
and paragraph
elements as a unit. Thus, the fragment
variable is a React element containing heading
and paragraph
as child elements. We will shortly understand why this is needed.
On line 10
, we specify the container
div
element which is found in index.html file, and then render fragment
within the container element.
At this point, you should understand the foundation upon which React was built. Its basic design mimics how we are able to dynamically manipulate DOM elements with native javascript. However, there is even more that React offers in dynamic manipulation of the DOM.
React JSX
So far, we have considered three ways in which we can write the code for our user interface that will be rendered in a web browser:
- Static HTML Elements
- Dynamic HTML Elements with native javascript
- Dynamic HTML Elements with React
Let us concentrate on the elements that were involved in producing our document page in the web browser. We only compare that of static HTML document and that of React.
For static HTML document, the following was all we needed inside <div id="container"></div>
:
<h1>Introduction to React</h1>
<p>React is a front-end javascript library used to build user interfaces.</p>
In the case of React, we had to dynamically create the elements before mounting them in the div
with id="container"
:
// create the heading and paragraph elements
const heading = React.createElement('h1', null, 'Introduction to React');
const paragraph = React.createElement('p', null, 'React is a front-end javascript library used in building user interfaces.');
// create the Fragment element that will wrap the heading and paragraph elements
const fragment = React.createElement(React.Fragment, null, heading, paragraph);
Now compare the case of typing the elements statistically in the html document file with creating them dynamically with React. You will agree that typing the elements in the html document file looks cleaner. Additionally, you are able to easily visualize what will be rendered on the page.
With this simple example, you may not readily see how typing the html elements directly in the source file helps visualize the application view. In large applications, those several React.createElement()
calls will make the source code look ugly and boring. You will also need to read and understand how the createElement()
calls are organised in order to visualise the application view.
If we are to replace those React.createElement()
calls with the html elements, we will have a better visualisation of the application view in the source code. For example:
// create the heading and paragraph elements
const heading = <h1>Introduction to React</h1>;
const paragraph = <p>React is a front-end javascript library used to build user interfaces.</p>;
Rather than assign each element to a separate variable, we can write several elements and wrap them as a unit, which we can assign to a javascript variable. See it below:
// create the heading and paragraph elements as a unit/fragment
const intro = <>
<h1>Introduction to React</h1>
<p>React is a front-end javascript library used to build user interfaces.</p>
</>;
What is that <></>
wrapping the elements, and why do we need it? In javascript, an expression should produce a single value which can be assigned to a variable. Since <h1>
and <p>
are separate elements, we need a way to wrap them as a single unit, and then assign to the intro
variable.
Think of <></>
as a wrapper or container that wraps several elements as a unit so that we can assign to a variable. It is the same idea when we use javascript arrays and objects as containers to wrap multiple values, then assign to a javascript variable. Do you remember we used React.Fragment
earlier in listing 16 to group multiple elements? <></>
is acutally a shorthand syntax for React.Fragment
which is used to wrap multiple elements as a unit.
One problem with using JSX is that it is not supported in native javascript, unless the elements are quoted string
s. To make it work means that there should be a way or an extension of javascript that supports it. Well, such extension already exists. It is called JSX (Javascript eXtension), or Javascript Syntax eXtension. Some refer to JSX as Javascript XML.
JSX enables us to use HTML-like elements directly in javascript source files for a better visual impression. But as earlier indicated, it is not supported in native javascript. Since most browsers do not understand JSX syntax for now, the elements will not be rendered on the page until we do further adjustment. Until then, your browser will report some errors in the browser console.
Update the content of your index.js file to the following and let’s see what happens:
// create the heading and paragraph elements as a unit/fragment
const intro = <>
<h1>Introduction to React</h1>
<p>React is a front-end javascript library used to build user interfaces.</p>
</>;
// get the container div element
const container = document.getElementById('container');
// create root object for container and render the intro
ReactDOM.createRoot(container).render(intro);
Refresh the document page in the browser. The heading and paragraph text disappeared, right? If so, then the reason is that the web browser doesn’t understand the JSX syntax we have introduced. Our aim was to introduce HTML-like elements in our javascript source file to have a better visual impression of our code. However, the browser doesn’t understand this JSX syntax. Think of this as two persons speaking different languages. To be able to communicate and understand each other, they will need a translator. In our case, we will also need a translator.
Transpiling with Babel
As earlier indicated, most web browsers do not understand JSX syntax. For applications with JSX syntax to be rendered on the page, we will need a translator that will convert JSX syntax code to native javascript code which the browser understands. One popular tool that is used for this is Babel.
Babel is a javascript compiler that is able to convert modern javascript syntax to backward compatible javascript code. Additionally, it understands JSX syntax and is able to convert JSX syntax code to earlier version of javascript code which most browsers understand.
To use Babel to translate our JSX syntax code, we will simply use a babel script. Go to babel standalone page, and under Installation section, copy the <script></script>
tag for babel:
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
In VS Code, click on index.html file, and paste above the script tag that includes our index.js file. After this, we have one more thing to be done.
You will notice that the script tag that loads our index.js has its type set to type="text/javascript"
.
<script type="text/javascript" src="./index.js"></script>
Since we want babel to read index.js file so that it will be able to convert our JSX syntax code to native javascript, we will need to change the type attribute to type="text/babel"
. Perform this update and save the file. This is shown below:
<script type="text/babel" src="./index.js"></script>
The content of index.html should read as shown in the following image:
You can see the inclusion of the <script></script>
tag for babel on line 15
. On line 17
, you can also notice that we have changed the type attribute of index.js file from text/javascript
to text/babel
.
After saving index.js file, you should refresh the page in your browser. This time, you should see the elements rendered on the page as expected. To explore further, let us include additional JSX syntax code.
In index.js file, add the following code right after initialising the intro
variable:
... // code for variable intro assignment here
// JSX for some javascript frameworks / libraries
const jsFrameworks = <>
<h2>Javascript Frameworks / Libraries</h2>
<p>
The following are some javascript frameworks/libraries used
in developing javascript applications.
</p>
<ul>
<li>React</li>
<li>Angular</li>
<li>Vue</li>
<li>Ember</li>
<li>Next.js</li>
<li>jQuery</li>
</ul>
</>;
This gives us two javascript variables containing JSX syntax code: intro
and jsFrameworks
. Take note of the characters {
and }
around intro
and jsFrameworks
variables on lines 26
and 27
respectively. If we need to execute any javascript expression within JSX syntax code, we will have to wrap the javascript expression in opening and closing braces.
To render the content of all the variables on the page, we will need a wrapper or container. This means we should wrap the two as a unit and assign to a single javascript variable.
Let’s wrap intro
and jsFrameworks
variables as a unit and assign to a different variable:
const content = <>
{intro}
{jsFrameworks}
</>;
The content of index.js file should now read as shown below:
// create the heading and paragraph elements as a unit/fragment
const intro = <>
<h1>Introduction to React</h1>
<p>React is a front-end javascript library used to build user interfaces.</p>
</>;
// JSX for some javascript frameworks / libraries
const jsFrameworks = <>
<h2>Javascript Frameworks / Libraries</h2>
<p>
The following are some javascript frameworks/libraries used
in developing javascript applications.
</p>
<ul>
<li>React</li>
<li>Angular</li>
<li>Vue</li>
<li>Ember</li>
<li>Next.js</li>
<li>jQuery</li>
</ul>
</>;
// a wrapper for intro and jsFrameworks variables
const content = <>
{intro}
{jsFrameworks}
</>;
// get the container div element
const container = document.getElementById('container');
// create root object for container and render the intro
ReactDOM.createRoot(container).render(intro);
From line 3
4, update the variable in the render()
method from intro
to content
. In this case content
is the overall container for all our user interface (UI) code.
// create root object for container and render the content
ReactDOM.createRoot(container).render(content);
After saving index.js and refreshing the document in your browser, you should see the page similar to the image that follows:
If you take a look at listing 26 above, you can tell that the source file is gradually being bloated with code. Introducing functions to handle certain aspects of the UI code will be a better idea. We need to move some parts of the source code to be handled by dedicated functions. For instance, we can take JSX code for intro
and jsFrameworks
to be returned from separate functions.
At the top of index.js file, lets write two functions, Intro()
and Frameworks()
, and let them return the JSX syntax code assigned to intro
and jsFrameworks
earlier:
function Intro() {
return <>
<h1>Introduction to React</h1>
<p>React is a front-end javascript library used to build user interfaces.</p>
</>;
}
function Frameworks() {
return <>
<h2>Javascript Frameworks / Libraries</h2>
<p>
The following are some javascript frameworks/libraries used
in developing javascript applications.
</p>
<ul>
<li>React</li>
<li>Angular</li>
<li>Vue</li>
<li>Ember</li>
<li>Next.js</li>
<li>jQuery</li>
</ul>
</>;
}
We can now assign the return values for Intro()
and Frameworks()
functions to intro
and jsFrameworks
variables. This will not change the rendered view in the browser window:
... // Intro() and Frameworks() functions
const intro = Intro();
const jsFrameworks = Frameworks();
// a wrapper for intro and jsFrameworks variables
const content = <>
{intro}
{jsFrameworks}
</>;
// get the container div element
const container = document.getElementById('container');
// create root object for container and render the content
ReactDOM.createRoot(container).render(content);
If we like, we can even call Intro()
and Frameworks()
functions directly in the JSX code assigned to content
variable, and then delete assignment to intro
and jsFrameworks
at lines 3
and 4
completely. See it below:
... // Intro() and Frameworks() functions
// a wrapper for intro and jsFrameworks variables
const content = <>
{Intro()}
{Frameworks()}
</>;
// get the container div element
const container = document.getElementById('container');
// create root object for container and render the content
ReactDOM.createRoot(container).render(content);
As can be seen, our application code is getting better and cleaner. But there is even an additional feature we can use. You already know that with JSX, we can use HTML-like elements directly in javascript files. Such elements include p
, div
, span
, input
, ul
, li
, and a lot of other elements you already know. But do you know that you can create your own custom elements and use them in JSX? Let’s explore further and see.
From listing 30, replace the function calls at lines 5
and 6
with the following:
<Intro />
<Frameworks />
Your updated code should read as follows:
... // Intro() and Frameworks() functions
// a wrapper for intro and jsFrameworks variables
const content = <>
<Intro />
<Frameworks />
</>;
// get the container div element
const container = document.getElementById('container');
// create root object for container and render the content
ReactDOM.createRoot(container).render(content);
You can see that we are using the function names without the braces, and also used the function names Intro
and Frameworks
to define our own elements. Now save the file and refresh the page. You should still be able to see the rendered page as before. Congratulations! You created your own custom elements.
In React terminology, your custom elements which you have defined above are called Components. Let’s discuss further on React Components to know different ways in which we can create them.
React Components
React components are individual pieces of the UI code that can be reused in other parts of the application. They return JSX code which describes a portion of the application user interface. They can also contain a piece of javascript code which is executed to obtain the final JSX syntax code that is returned.
In listing 30, we used the function names Intro()
and Frameworks()
as custom elements (<Intro />
and <Frameworks />
) to return JSX code. This implies that we can describe React Components as custom elements for building parts of the application UI.
React needs a way to differentiate between custom defined elements (Components) and standard HTML elements such as div
, span
, p
, etc. React components names must always begin with a capital letter. Yes, that’s how React gets to know of your components. Standard HTML-like elements on the other hand must always be in lower case letters, for example, div
, span
, nav
, u
l, etc.
React Components can be created using function
or class
definitions. In the next section, we will look at how we can create components with function
and class
syntax.
Function Components
A function component is simply a javascript function which returns a ReactElement
object, such as JSX elements we saw earlier. As it is a javascript function, it can take arguments (properties) just as other javascript functions accept arguments.
In listing 28, we defined Intro()
and Frameworks()
functions which returned JSX elements that describe parts of the application user interface.
function Intro() {
return <>
<h1>Introduction to React</h1>
<p>React is a front-end javascript library used to build user interfaces.</p>
</>;
}
function Frameworks() {
return <>
<h2>Javascript Frameworks / Libraries</h2>
<p>
The following are some javascript frameworks/libraries used
in developing javascript applications.
</p>
<ul>
<li>React</li>
<li>Angular</li>
<li>Vue</li>
<li>Ember</li>
<li>Next.js</li>
<li>jQuery</li>
</ul>
</>;
}
Once the function components have been defined, they can be used as custom elements in any part of the javascript file where their elements need to appear in the application UI:
<Intro />
<Frameworks />
Recall that custom component names must start with a capital letter. That is how React differentiates between your custom elements and regular HTML elements. Therefore, we named our custom components Intro
and Frameworks
to begin with capital letters.
Class Components
An alternative way to define React Components is through the use of javascript class
syntax. Like function components, the name of the class becomes the name of the component. Again, class
components can also be considered as a custom elements.
If we create React components using javascript class
syntax, then it is mandatory for the class
component to have a method named render()
. This is the method that React will call to return the piece of UI code for the component. Therefore, in the render()
method, we will have to return the piece of the UI code for the component.
The following code listing shows a sample class
component that returns user interface code for React’s first release date.
class ReleaseDate extends React.Component {
render() {
return <>
<h2>Release Date</h2>
<p>React's first release was on May 29, 2013.</p>
</>;
}
}
In listing 35
, we use the class
syntax to create our own React component. When creating a component this way, the class must inherit from the Component
base class of React using the extend
keyword. As indicated earlier, the class must define the render(
) method in order to be considered as a valid class component. The render()
method is what will be called to return the UI code for the component.
Suppose you have defined the ReleaseDate
class component in the source file, then we can go ahead and use the class name as a custom element. Let’s insert the custom element <ReleaseDate />
between <Intro />
and <Frameworks />
elements so that we can have the release date after the introduction.
... // Intro() and Frameworks() functions and ReleaseDate class
// a wrapper for intro and jsFrameworks variables
const content = <>
<Intro />
<ReleaseDate />
<Frameworks />
</>;
// get the container div element
const container = document.getElementById('container');
// create root object for container and render the content
ReactDOM.createRoot(container).render(content);
After saving index.js and reloading the document page in your browser, your page should look similar to the following image:
As can be seen, the <ReleaseDate />
class
component has been rendered between <Intro />
and <Frameworks />
components. The application’s view has been rendered based on the arrangement of the components.
Whether you choose to use function
or class
components is a matter of taste. However, there are some features of class
components which aren’t available in function
components. For instance, you can call the method setState()
to update the state of a component variable in class
components. With function
components, setState()
method is not available. The workaround is to define our own state management functions. As that is an intermediate to advanced concept, we will not consider it in this introductory post.
Summary
In this post, we have gone through the basics of developing the web application interfaces with React. The practical examples covered so far has highlighed how React works closely with dynamic manipulation of the DOM.
To be able to use custom elements and HTML-like elements in javascript, we are able to write our code in JSX syntax code. Since JSX syntax code is new and most browses don’t support it yet, we need to use tools like babel compiler to convert our modern javascript code to earlier versions of javascript which most browsers understand.
In React, we can create our own elements, commonly known as Components and use them in building our application user interface. React components can be defined either using function
or class
declaration syntax. React components return ReactElement
s, such as JSX code.
In a separate post, we will look at how we can build React components and applications by using build tools rather than React and babel scripts.