As a developer painful and frustrating occurrence every front-end developer will agree with has to be writing lines of code to do a specific task at multiple places. An easy example is placing a submit button on a page which will be replicated on other pages such as the registration page, signup page, comment page, etc.
An urgent need for a framework or library that allows developers to break down complex codes into simple and reusable chunks called components for easier, faster, dry, and efficient deployment in their projects. Hence the creation of Reactjs to solve such complicated problems.
Introduction to ReactJS
Reactjs is an open-source JavaScript framework/library developed by Jordan Walke of Facebook in 2011 to enhance the user interface in mobile and web applications and systems. Jordan Walke was a software engineer at Facebook, who developed and released the early prototype of React and called it “FaxJS”.
The creation of React was influenced by XHP, an HTML component library for PHP. React was first developed and used on the Facebook newsfeed, then deployed to be used on Instagram in 2012 before its official release to the public, and made open source in 2013. Today ReactJS is the most in-demand and in-use JavaScript framework used in developing dynamic and complex applications that consume a huge block of data rapidly.
An outstanding beauty of React is it is component-based, this allows complex code to be broken down into individual pieces which help developers structure their codes in a better and reusable way. Another cool feature of React is its ability to display the part of a user interface that is changing without rendering the whole page, this makes the user experience much smoother and faster.
Prerequisites before learning ReactJS
- Basic knowledge of HTML, CSS, and JavaScript.
- JavaScript ES6 Fundamentals.
- NodeJS and Command line fundamentals.
- Code Editor.
HTML, CSS, JavaScript
The journey into Frontend development begins with the basics of HTML, CSS .and JavaScript. These are the foundations of frontend web development and there all work together to create a smooth, dynamic, and fully functional website/application. In my previous articles, I have explained in detail how to go about becoming a front-end developer. Also a basic knowledge of HTML for beginners.
A brief explanation of the basic frontend languages will be given for a clear understanding of the task ahead.
HTML
HTML simply means Hyper Text Markup Language. This is a web-based markup language that defines the structure of contents in a web page. It is considered the ‘skeleton’ of the body (web page) that directs and structures the content of web pages.
CSS
CSS is fondly called the ‘Skin’ of the web because it defines the style in which a web page will appear. CSS is used to add beauty to a website or application by using some properties such as height, width, color, etc. to the specific section.
JavaScript
JavaScript is the ‘Brain’ of a web page which is described as “the language that powers the web”. JavaScript defines and controls the functionalities and effects of the website or application.
In so many websites and applications today we can see maps, 2D/3D animations, graphics, etc.
It is evidence that JavaScript was used in creating those functionalities and effects.
ES6 Fundamentals
ES6 is the version of JavaScript that was launched in June 2015 and comes with a lot of features. Basically, to get a foothold on React it is important to grasp some key features such as:
- Arrow function
- Let and Const -Class and ‘this’ keyword.
Arrow Function: This function allows a developer to write shorter and simpler function syntax. It makes the code appear clean and more readable.
//old JS
function name (){
console.log(“my name is Nonso”);
}
name();
or
var name = function () {
console.log(“my name is Nonso”);
}
name();
//ES6
Var name = () => {
console.log(“my name is Nonso”);
}
name();
Let and Const: In replacement of the ‘var’ keyword, Let and Const were introduced into JavaScript ES6.
- Let defines a local variable limiting their scope within the block there are declared in.
- Const defines a constant variable whose values cannot be assigned again.
- Class and ‘this’ keyword: These are Object Oriented Programming concepts such as class, method, Objects, etc.
NodeJS and Command line fundamentals.
A lot of developers consider NodeJS a programming language which is not true. NodeJS in simple terms is just an execution programming environment for JavaScript. Every browser has a JavaScript engine embedded in it such as the Chrome V8 engine, Mozilla Firefox has SpiderMonkey. Outside the conventional browsers, you cannot perform any operation such as OS operations, file operations, Network operations, etc. this is the reason Node was developed. Embedded in it is the Chrome V8 engine which allows Node to perform operations outside of the browser.
Some features of Node are :
NPM (Node Package Manager): NPM is a node installation package manager which installs node modules and packages into a project.
IMPORT and EXPORT keywords.
Import: After installing Node modules using npm in a project, the “import” keyword would have to be used in other to make use of the packages. Export: When creating a module the ‘Export’ keyword is used and returns a single part because not all the methods are needed.
All we have discussed above were prerequisites of Reactjs. Moving forward, we will give a brief explanation of the 4 concepts or fundamentals to get grounded in React.
These fundamental concepts are:
- Components
- JSX
- State
- Props
What are React Components?
Earlier before the introduction of React developers had to write hundreds of lines of code for a simple application or website. Most of these applications and websites followed the conventional DOM structure in which making changes can be very ridged and demanding for developers. Thus, the component-based approach was introduced. In this approach, the complex code is divided into chunks called components.
In a house, we have various sections such as the kitchen, bedroom, dining room, etc. these sections (components) have various functions and work independently of the other. React components are the core building blocks of any react application. It is lite, dry and reusable which gives it the ability to work independently by breaking down complex codes into smaller pieces of UI that hold data (state) and render HTML based on the data rendered.
There are two types of components:
- Function Components
- Class Components
Function Components
A functional component is simply an ES6 function that returns a special JavaScript syntax called JSX or React element. In simple terms, a functional component is a JavaScript function that accepts props and returns a react element. This is the simplest and recommended way to create a component in react.
After the release and introduction of React Hooks, functional components have become a standard way of writing React components in modern-day applications.
Whenever a JavaScript function is written, we can create a functional component for React where data can be passed as parameters to the function created. The return value in a functional component basically is the JSX code that is rendered to the DOM
Import React from ‘react’
export default function Hello(){
return (
<div>
Hello World!!
</div>
)
}
Class Components
Class components is also an ES6 class that has a render() method that returns JSX which also accepts props in the constructor when needed. The Class Component is the second type of component which was mostly used because “state” could not be used inside functional components which were only used for UI rendering and the class component was used for data management. The introduction of React hooks has made it possible to use states in functional components as well.
import React, { Components } from ‘react’;
export default class Hello extends Component {
render () {
return(
<div>
Hello World!
</div>
)
}
}
Some advantages of React components are:
- Re-usability: When an entire application is divided into smaller parts, it is easier to locate, identify, and use pre-existing functionalities in the code.
- Maintainability: It is easy to locate a well-organized component quickly and make possible changes and updates because the codes have been Witten in different components.
- Scalability: Ensuring that components are properly namespaced can help to avoid errors and overlapping of functionalities into wrong palaces as the project is scaled up.
- Ease of Integration: This is one of the best advantages of React Component because, project codes are written and uploaded into repositories such as Github, which is an open-source tool.
Developers can pick parts of these codes needed for a particular project modify them and make effective use of them.
JSX
JSX stands for JavaScript XML, it is a JavaScript Extension syntax that is used in React to easily write HTML and JavaScript together. JSX is the syntax of JavaScript that is used in React to design user interface (UI). It is a kind of templating language but with the abilities of JavaScript.
JSX provides a developer to write HTML/XML-like structures such as DOM structures in the same file where JavaScript codes are also written. The preprocessors will then transform these HTML-like syntaxes into actual JavaScript objects that can be run by a JavaScript engine. Just like HTML, JSX has tags and attributes also. Below is a simple JSX sample code.
Import React, {Component} from “react”;
Class Main extends React,Component {
render( ) {
return <h2 className=”tittle”> Hello World!</h2>;
}
Export default Main;
Rules for writing JSX
- All HTML tags must have a closing tag.
- JavaScript codes must be wrapped in {}
- To name HTML attributes or CSS properties, we must use CamelCase.
- Ternary operators are used in place of if-else statements.
Advantages of JSX
- Writing HTML codes inside JSX becomes easier and faster.
- Ease of converting HTML tags into React codes.
- Most errors can be found at compilation time because JSX is fast-save.
- HTML elements can also be used in the DOM irrespective.
- JSX prevents cross-site-scripting (injection attacks) attacks.
Disadvantages of JSX
- If HTML elements are not properly closed, JSX can turn in errors.
- Converting JSX into ES6 and other forms due to the inability of web browsers to understand it (though with the release of babel, this issue has been worked on).
State
With the introduction of React it is now possible to create a state and maintain form inside the functional component. This has been made possible with the introduction of React Hooks, this is a new feature that allows developers to use “hook” functionality in functional components. The state is considered the ‘Brain’ of every React component which determines how a component will behave and render values.
Components generally take in props and render them, this term is called ‘stateless component'. These components can also be used to store data sets and information about the component which can be changed over a period of time. Such a component is called a ‘stateful component’, in this component changes happen as a response to a system event.
State is responsible for making and keeping a component simple, dynamic, and interactive as possible. Variables can be accessed and printed in a JSX with a curly brace {}, while state can be accessed using the reference 'this.state'. Similarly, 'this.state' can be rendered inside render( ) by setting a default state for component.
import React, {useState} from “react”;
import ReactDOM from “react-dom”;
const MyComponent = () => {
const [value, setValue] = useState(1);
return
<div>
<p>(value)</p>
<button onClick={( ) =>
setValue((value + 1))}> Increment Value</button>
</div>
);
};
In the code above we can see how easy it is to create and update the state in the functional components using the useState( ) hook. ReactHooks enables developers to make use of React Function Components using the arrow function.
Props
Props are simply properties that work similarly with HTML attributes and are read-only components. Through props, data set can be passed from parents to child component. In this concept, the User interface (UI) is segmented in a tree formation where the parent components become the root and the child components become the branches and sub-branches. In the transferring of data from parent component to child component deeply nested, you cannot pass down property directly to the targeted child component or from the child component to the parent component.
React follows a rule where properties have to flow down the parent component directly to the closest (immediate) child component. In this way, you cannot skip a layer when sending data to the child component or back to the parent component. This makes React a one-way data binding technology where data is sent layer by layer until it gets to the targeted component.
Import React from “react”;
import React from “react-dom”;
class MyComponent extends React.Component{
render(){
return(
<div>
<h1>Hello World!</h1>
<Header name=”Myprops” id=”101”/>
</div>
);
}
}
Function Header(props){
return (
<div>
<Footer name={props.name} id={props.id}/>
</div>
);
}
Function Header(props){
return (
<div>
<h1> Welcome : {props.name} id={props.id}</h1>
<h1> id is : {props.id} </h1>
</div>
);
}
RenderDOM.render(<MyComponent/>,document.getElementByid(“content”));
Conclusion
In this article, we have been able to learn how components, arrow function, state, and props work in React. We have seen the two types of function and how to pass data from one to another making use of props. React functional components are so beautiful because with the introduction of React 16, using hooks it is possible for so many things that were not imaginable before now.
Here is a free video material that I think will aid your react journey Freecodecamp