React is a popular Javascript Framework used in creating interactive, dynamic and data intensive User Interfaces. It is not the only Javascript Framework, there are others like Vue.js, Angular, Svelte and others. Amongst its peers, React remains the most popular and in my opinion versatile. It does have it’s shortcomings like every technology but it’s declarative approach along with it’s ease of use in both displaying and consuming data from external or internal APIs make it my favorite.
In this chapter, I’d be building a simple Profile Page Application inspired by Wikipedia Pages and in the process cover such topics as:
- JSX
- Development Environment
- JSX Rules
- Components
- Nested Components
My approach to covering this framework would be to first display the code in total then begin to analyse each line along the way, touching on the various sub-topics.
import React from "react";
const Biography = () => {
const name = "Obafemi Awolowo";
const summary = `Chief Obafemi Jeremiah Oyeniyi Awolowo
GCFR (Yoruba - Ọbáfẹ́mi Oyèéníyì Awólọ́wọ̀ 6 March 1909 – 9 May 1987)
was a Nigerian nationalist and statesman who played a key role in
Nigeria's independence movement (1957-1960). Awolowo
founded the Yoruba nationalist group Egbe Omo Oduduwa, and
was the first Leader of Government Business and Minister of
Local Government and Finance, and first Premier of the Western
Region under Nigeria's parliamentary system, from 1952 to 1959.
He was the official Leader of the Opposition in the federal parliament
to the Balewa government from 1959 to 1963.`;
const earlyLifeContent = `Obafemi Awolowo was born Jeremiah Obafemi
Oyeniyi Awolowo on 6 March 1909 in the Remo town of Ikenne,
in present-day Ogun State of Nigeria.He was the only son of
David Shopolu Awolowo, a farmer and sawyer, and Mary Efunyela Awolowo.
He had two sisters and one maternal half-sister. Awolowo's father was
born to a high chief and member of the Iwarefa, the leading faction of
the traditional Osugbo group that ruled Ikenne. In 1896, Awolowo's father
became one of the first Ikenne natives to convert to Christianity.
Awolowo's paternal grandmother, Adefule Awolowo, whom Awolowo adored,
was a devout worshipper of the Ifá. Adefule, Awolowo's grandmother,
believed that Obafemi was a reincarnation of her father
(his great-grandfather). Awolowo's father's conversion to Christianity
often went at odds with his family's beliefs. He often challenged
worshippers of the god of smallpox, Obaluaye. His father ultimately
died on April 8, 1920, of smallpox when Obafemi was about eleven years old.
He attended various schools, including Baptist Boys' High School (BBHS),
Abeokuta; and then became a teacher in Abeokuta, after which he
qualified as a shorthand typist. Subsequently, he served as a clerk at
the Wesley College Ibadan, as well as a correspondent for the Nigerian
Times. It was after this that he embarked on various business ventures
to help raise funds to travel to the UK for further studies.
Following his education at Wesley College, Ibadan, in 1927,
he enrolled at the University of London as an External Student
and graduated with the degree of Bachelor of Commerce (Hons.).
He went to the UK in 1944 to study law at the University of London
and was called to the Bar by the Honorable Society of the Inner Temple
on 19 November 1946. In 1949, Awolowo founded the Nigerian Tribune,
a private Nigerian newspaper, which he used to spread nationalist
consciousness among Nigerians.`;
const earlyLife = "Early Life";
return (
<>
<div>
<h1>{name}</h1>
<br />
<section>
<p>{summary}</p>
</section>
<br />
<section>
<h3>{earlyLife}</h3>
<p>{earlyLifeContent}</p>
</section>
</div>
</>
);
}
export { Biography };
The development environment I’m using is CodeSandbox. You can open a free tier account with them here. I chose this environment because since I’d be building web applications, it felt intuitive to use an online integrated development environment (IDE). There are other options, you could also create a local development environment using such code editors like Visual Studio Code(recommended), Sublime etc. But I chose CodeSandBox and I’d advise you do same to follow along.
When you’ve registered with CodeSandbox, the first thing you need to do is to select a new sandbox, from the display tiles either select React or type React in the search bar. Note, do not select React with Typescript but just React.
As soon as this is done, you’d be directed to your personalised sandbox. In the left panel, scroll down to the last items, you’d see a package.json file – this is a file that contains vital information about your application and other configuration details like app publisher, license, dependencies, scripts etc – we are interested in adding a new key value pair to enable us use ES6(EcmaScript6). Anywhere in the first object add this code:
"type": "module",
Save the file then exit or close the package.json file. With that configuration set, we can start building the Profile Page Application.
The first line in the code enables us to use React using the import statement. It is compulsory to include this line in your JSX files. Yes, I mentioned JSX; what is JSX?
JSX
JSX is a programming language invented by the React team at Facebook (this is where React was created), it is a syntax extension to Javascript. It is similar to template languages like Embedded Javascript(EJS) or pug but not entirely. It defers in the sense that JSX enables us to build React elements. Also, with JSX we can input HTML into the code without the usual workaround when using plain vanilla Javascript. An example is shown below:
Without JSX:
In html file:
<script>
document.querySelector(".no-jsx").innerHTML = "Hello World!";
</script>
<div class="no-jsx">
</div>
With JSX:
const helloWorld = () => { return <div>Hello World!</div>; }
The main difference you’d notice in the above code was that with JSX, there was no need to define the structure of the page with html before we could begin to access the elements and change their structure. This is the power of JSX and react and it’s also a fundamental way of building the elements on your page, layering each element on top another.
Before we continue with discussing the Profile Page Application code, there are a few guidelines about using JSX:
- JSX file extensions should end with .jsx and not .js
- It is good practise to use Pascal Case when naming your .jsx files e.g Profile.jsx, ProfilePage.jsx etc with each word starting with a capital letter.
There are more guidelines and style guides and if this interests you, the Airbnb React/JSX style guide is a good reference point. I haven’t read all of them. The two listed above have seemed to be just fine.
In the third line, we have an arrow function called biography, while this is a function but in react we call such functions that return something – Components. Before going further, let’s talk about this important React element called Components.
Components
Components are functions that return something. A component must return something and only one thing. Do not fret, if you notice when writing html code, a lot of components are layered on top of one another:
<!DOCTYPE html>
<html>
<head>
<title>HTML Layers</title>
</head>
<body>
<h1>HTML Layers</h1>
<p>Example of HTML Layers</p>
<ul>
<li>Another Layer</li>
</ul>
</body>
</html>
You can see in the above html code that there is a layered structure, we have the overall <html> tag and in it we have the <head> which has a <title> then the <body> which has <h1>, <p> etc. In the same way we can build out our components or user interface elements using Components.
const HtmlLayers = () => {
return (
<div>
<h1>HTML Layers</h1>
<p>Example of HTML Layers</p>
<ul>
<li>Another Layer</li>
</ul>
</div>
);
}
In the above HtmlLayers component, it returns only one <div> but has other html elements nested inside of it. This is exactly what we’ve begun to do in the Biography Component, we have defined a function, and made it return various elements of what we want the Profile Page Application to have. These elements include a name(line 4), summary(line 6), early life content(line 17), and sub-heading title(47). These are the four UI elements we want to have on each page.
In Line 49, we have the return statement which returns an empty react tag(<></>) then in it, there’s a <div> which then returns the different UI elements we want rendered on the page.
After this, the last line exports this component from the .jsx file so it can be imported into another file which is the index.js. Let’s touch on the index.js file.
import React from "react";
import { createRoot } from "react-dom/client";
import { Biography } from "./reactbyprojects/Chapter 1/ProfilePage";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(<Ede />);
So, I haven’t been entirely honest with you. Yes, we may not need a lot of html files but we do need one html file, this is where we’d plug react into, a sort of root for react to tap into the whole web application. Fortunately, because we are using CodeSandbox, this has been automatically created for us along with the index.js file but it’s important to understand certain elements of this files.
The most important line in the index.html file is where the id named root is. This is usually in a <div> tag but you can put this id anywhere in your web application. However, it must be named “root” (this may be a convention).
In the index.js file, we have top level import statements importing react, createRoot and the name of your application file. In our case Profile Page. We tell react where to find this file; this is what line 3 does. You can choose to add the extension at the end or not, if the name is unique and matches the file path, React would get the file.
The rest of the code is intuitive, we tell react to grab an element whose id name is root then we wrap this variable inside the createRoot function and lastly, we add a render method to this variable. Most times in the wild, this is how the whole application would be wrapped in the index.js file, with a lot of modularity going on behind the scenes.
We still have one more important topic before we finish this chapter, which is Nested Components. We’d be adding more complexity to our Profile Page Application to make it more robust and dynamic. The image below is the final output of the Profile Page Application.