In This React Js Tutorial we will cover the basic and advanced concepts of React JS. Let us start by getting an overview of what we’ll be going through in this React JS Beginner Tutorial.
Let us begin with an overview of what we are going to cover in this React JS tutorial
React Js Tutorial Project Source Code
What is ReactJS?
According to the official React Documentation, React is defined as A JavaScript library for building user interfaces.
React JS is one of the most widely popular open-source JavaScript libraries developed by Facebook. It is responsible for managing the view layer for both web and mobile-based applications. The primary use of React is in building reusable UI components.
React JS is user-friendly and therefore has a strong foundation and community behind it.
What is the use of ReactJS?
The main feature of ReactJS is developing a User Interface (UI) to improve application speed. The JavaScript virtual DOM, which is faster than the regular DOM, makes it possible to enhance its performance.
A ReactJS application consists of multiple components, where each is responsible for producing a small, reusable part of HTML code. You can nest these components with other ones to build complex applications with simple building blocks.
React’s component and data patterns boost readability and help handle large applications. You can make use of ReactJS on both the client, server-side, and other frameworks.
Why learn React JS?
There are several JavaScript frameworks available, but React is one of the most popular ones among them. The difference between the older frameworks and React is that the former ones use a traditional data flow structure, using the DOM (Document Object Model).
But, what is DOM? A browser creates objects every time you load a web page. Data is added or removed at the back end after any modifications, and every time a new DOM is created for the same page. Hence, memory is wasted unnecessarily due to the repeated procedure, leading to reduced application performance.
To solve the above problem, Facebook invented ReactJS. Although it still follows the traditional data flow structure, it does not directly operate on the browser’s DOM (Document Object Model) but a virtual DOM instead. Therefore, it fixes any DOM changes built and run in the memory itself.
Features of React JS
- JSX: It is a JavaScript syntax extension. JSX stands for JavaScript XML. Although it is not necessary to use JSX, it is recommended to use it.
- Components: Components are the core of React. They are essential when you are handling the code for large-scale projects.
- One-way data-binding: React applies a one-way data-binding or a unidirectional data flow. The advantage of this is that it gives the user better control over the application. Flux ensures the unidirectional flow of data. It increases efficiency by improving the application’s flexibility.
- Simplicity: The JSX file in ReactJS simplifies the application.
- Performer: React’s performance is excellent. The main reason behind it is that it uses a virtual DOM, unlike the other frameworks.
- License: ReactJS is licensed under Facebook Inc.
Advantages of ReactJS
Here are important pros/benefits of using ReactJS:
- It is user-friendly. React provides its users with helpful documentation, training resources, and in-depth tutorials.
- You can quickly build dynamic web applications with ReactJS as it offers high functionality. It uses the JSX (JavaScript Extension) that allows you to create an app with minimal coding.
- React’s components are reusable, which makes it easier to develop and maintain your apps.
- React provides its developers several handy tools.
- React uses a virtual DOM. This JavaScript object improves the app’s performance because the virtual DOM is faster than the regular DOM.
- You can use React on the client, server-side, and other frameworks as well.
- The data and component patterns in React optimize readability, which is useful when handling larger apps.
Disadvantages of ReactJS
Here are the cons/ drawbacks of using React JS:
- To obtain the complete development toolset, you have to choose different technologies since React covers only its view layer.
- Developers usually do not prefer React’s usage of JSX and inline templating.
- Developers might find it challenging to adopt continuous updates in React. They have to keep upgrading their skills to keep up.
- Since React is a continually updating technology, it isn’t easy to make proper documentation for it. Therefore, developers usually end up writing instructions on their own.
Install React Js
There are two main ways to install the React JS.
1. Using the npm command
Steps to follow to install ReactJS using the npm command are:
1. Install Node JS and NPM. They are platforms that are required to develop ReactJS applications.
2. Install React and React DOM.
- Make a root folder and name it reactApp.
- Create a package.json file.
- Install react along with its DOM packages
3. Install Webpack. Its functions include module packaging, development, and production pipeline automation.
4. Install Babel. It is a JavaScript transpiler and compiler that converts one source code to others.
5. Add the files—index.html, App.js, main.js, webpack.config.js, and .babelrc in your project folder.
6. Configure webpack in the webpack.config.js file.
7. App.jsx and main.js is the first React component.
8. Create a .babelrc file.
9. After the installation process is complete and you set up the app, you can start the server.
10. Generate the bundle for your app. Bundling is when you follow imported files and merge them into a single file? called?a bundle.
2. Using the create-react-app command
Steps to follow to install ReactJS using the create-react-app command are:
- Install NodeJS and NPM. They are platforms you require to develop ReactJS applications.
- Install React using the .npm package manager.
- Create a new React project using the create-react-app command.
- After you complete the installation process, you can now start the server.
What is React JSX?
ReactJS is a JavaScript extension. With this template script, you can use HTML and JavaScript together.
An example of a JSX code is:
const h1tag="<h1>Hello, from Mindmajix Tutorials! </h1>";
Reasons to use JSX in React
In React, you can write HTML/XML structures in the same file as the JavaScript code. Then, the preprocessor converts the expressions into JavaScript code. Additionally, you can also manage the state changes in the dom in the most effective manner.
JSX tags include a tag name, attributes, and children.
Some of the reasons to use JSX in React are:
- It works at a more incredible speed than regular JavaScript. While it translates the code to JavaScript, it also performs optimization.
- It makes use of components that include both markup and logic.
- You can find the errors during the compilation time as it is type-safe.
- You can easily create templates in JSX.
Components in React JS
Components are the core building blocks of React applications. They are logical groups of code that make up the entire application. With the use of components, you can build UIs quickly. Every component works independently, and you can merge them into a parent component.
React components have their unique structure, methods, and APIs. Additionally, they are also reusable.
There are two types of components in ReactJS:
- Functional components
- Class components
1. Functional Components
You can only write components using a render method with functional components. These are JavaScript functions that may or may not receive data as parameters. Functional components are also called stateless components since they do not manage the local state. Given below is an example of a functional component:
function WelcomeMessage(props) {
return <h1>Welcome to the,{props.name}</h1>;
}
2. Class Components
Class components are more complicated than functional components since you have to extend from React. They are also called stateful components since they manage the local state. You can perform the following with class components:
- You can move data from one class to another class component.
- You can create a class by defining a class that has a render function.
Given below is an example of a class component:
class MyComponent extends React.Component {
render(){
return(
<div>This is main component.</div>
);
}
}
Props in React JS
Props are nothing but properties you can use inside a component. They are read-only variables that store the value of attributes of a tag. Props are similar to function arguments because you can pass them to the components in a similar way as arguments.
You cannot modify props from inside the components. Instead, you can add attributes called props.
Props to Function Component:
Given below is an example of moving props to a function component.
import React from 'react';
import ReactDOM from 'react-dom';
function Hello(props) {
return <h1>{props.msg}</h1>;
}
const Hello_comp = <Hello msg="Hello, from Mindmajix Tutorials!" />;
export default Hello_comp;
As you can see in the above example, the msg attribute is added to the <Hello/> component. You can also access it as props inside the Hello function. It will include the details of the msg attribute.
Component Life Cycle in React Js
There are four phases in a component’s lifecycle. They are:
- Initial phase
- Mounting phase
- Updating phase
- Unmounting phase
1. Initial Phase
This phase is considered the birth phase in a ReactJS component’s lifecycle. In this, the component begins its way to the DOM. During this phase, the component includes both default Props and the initial State.
The initial phase includes the following methods:
- getDefaultProps(): It defines the default value of this.props.
- getInitialState(): It defines the default value of this.state.
2. Mounting Phase
In the mounting phase, you create the component instance and insert it into the DOM. It has the following methods:
- componentWillMount(): You call this method before the rendering of a component into the DOM. The component will not re-render when you call setState() in this method.
- componentDidMount(): You call this method after rendering a component and placing it on the DOM. Then, you can perform DOM querying operations.
- render(): You define this method in every component. You cannot return a single root HTml node element. However, you can return a null or false value if you don’t want to render anything.
3. Updating Phase
In this phase, you can handle the user interaction and communication with the hierarchy of components. In this phase, the priority is to make sure that the component’s latest version is displayed. Unlike the previous stages, the updating phase repeats over and over again. It includes the following methods:
- componentWillReceiveProps(): You call this method when a component receives a new prop.
- shouldComponentUpdate(): You call this method when a component decides it wants to make changes to the DOM. You can control the component’s behavior when it gets updated.
- componentWillUpdate(): You call this method before the component update. You cannot use the this.setState() method to change the component state. Further, if shouldComponentUpdate() returns false, then this method will not be called.
- render(): You call this to inspect this.props and this.state. It returns any of the following: Arrays and fragments, String and Number, Booleans or null, React elements.
- componentDidUpdate(): You immediately call this method when the component is updated.
4. Unmounting Phase
The unmounting phase is the last phase of the React component lifecycle. It is invoked in a situation when a component instance is unmounted and destroyed from the DOM. It contains only one method, as given below:
- componentWillUnmount(): You call this component before a component is unmounted and eliminated permanently. This method performs cleanup tasks like event listening, canceling network requests, invalidating timers, cleaning up DOM elements, etc.
React Hooks
This new feature was added in React version 16.8. With the help of React Hooks, you can write the React features without using the classes. React hooks allow you to write less code and that makes your app efficient, simpler, and powerful.
You will be working on mainly 5 core concepts of React Hooks. These five core concepts are given below:
useState: Most of the time in your React app you will be using this concept to store and manage the data.
useEffect: You will be using this concept in actions like HTTP requests and working with the Browser API.
useRef: This will be used to reference JSX elements.
useContext: This property of React Hooks will be used to access data from React Context to share data among components easily (instead of passing props)
useReducer: This concept in React hooks will be used to store and manage data across multiple components.
We have discussed only 5 hooks that are important to learn. There are more than 5 hooks but that’s not needed initially in your learning phase. As you will progress and you will encounter problems in your application, you will be learning more hooks slowly.
Redux
In your React application, you will have to manage the states. Once your application will start growing it will become a complex application and you will have to manage the states across components.
Redux which a powerful JavaScript library solves this problem and helps in maintaining the state of the application. In Redux, you store all your states in a single source.
You can learn more about Redux in the Official Redux tutorial.
React Router
React developers use a third-party library called react-router-dom to create links for different pages, to load the content of different pages, and to redirect to other pages.
Below are some common features of react-router-dom you should know about to work with your application.
How to use , and components.
How to do navigation using the component and using the useHistory() hook.
Creating dynamic routes using the path prop i.e. and getting the path values using the useParams() hook.
How works in React Router.
React Forms
Forms are useful in web applications as they make it possible for the users to interact with the application. They can perform various tasks such as adding users, searching, filtering, ordering, booking, etc. Forms can contain elements such as text fields, buttons, radio buttons, checkboxes, etc.
Creating Form in ReactJS
In ReactJS, the component handles the React form. There are two different types of forms:
- Controlled components
- Uncontrolled components
Controlled components | Uncontrolled components |
In controlled components, the parent component controls the data. | In uncontrolled components, the DOM handles the data. |
It permits validation control. | It does not permit validation control. |
Here, the internal state is not maintained. | Here, the internal states are maintained. |
It accepts current values as a prop. | It uses a ref for its current values. |
It holds better control over the elements and data in forms. | It holds limited control over elements and data in forms. |
ReactJS Events
Events are actions that are triggered by either system-generated events or user actions. A few examples of events are loading a web page, resizing a window, pressing keys, etc.
React’s event handling system is called synthetic events and is similar to the system on DOM elements.
You can use the setState() method to update the state during user interaction with an HTML element.