React JS Tutorial - Learn React JS step by step

Unlock the Power of ReactJS Components 4: Best Practices and Tips

No comments

Loading

ReactJS Components: Nowadays, the buzzword in the industry is “React,” so today I thought of writing on React. In this article, I will explain the real-time example of the React component (learn the basics of React in 10 minutes). At the end of Part 1 and Part 2, you will be confident enough to go to the next level of React.js learning. This will give you the right perspective.

Key-Highlights: React JS Tutorial

  • Introduction of React.js
  • Where did the name React in React.js come from?
  • The History of React.js and Why Should We Use React.js?
  • What are the prerequisites to learning React.js?
  • Understanding React.js Components
  • A real-time example of a component – any website home page
  • React Component Types
  • React Life cycle Methods (Diagram)

Introduction: ReactJS

ReactJS, also known as React, is a popular JavaScript library for building user interfaces. It was developed by Facebook and is widely used in the web development industry. ReactJS provides developers with a powerful and efficient way to create dynamic and interactive applications by breaking the user interface into reusable components.

At the core of ReactJS lies the concept of components. ReactJS components are modular, self-contained units that encapsulate specific functionality and user interface elements. These components can be thought of as building blocks that can be combined and reused to create complex UIs.

ReactJS components offer numerous advantages over traditional approaches to building user interfaces. By breaking the UI into components, developers can manage their code more effectively, promote reusability, and improve maintainability. Each component in ReactJS has its own state, allowing developers to manage and update specific parts of the UI independently, without affecting the rest of the application.

One of the key features that make ReactJS components stand out is the virtual DOM (Document Object Model). ReactJS uses a virtual representation of the DOM, which allows it to efficiently update only the necessary parts of the UI when changes occur. This approach minimizes the need for full page reloads and ensures optimal performance.

ReactJS components can be classified into two types: functional components and class components. Functional components are simple, stateless functions that receive data as input and return UI elements. Class components, on the other hand, are ES6 classes that have additional features like local state and lifecycle methods.

The ReactJS ecosystem is rich with a vast array of pre-built, community-contributed components that developers can leverage to speed up development. These components cover a wide range of functionalities, from basic UI elements like buttons and forms to complex components like data grids and charts. ReactJS components can be easily integrated into existing projects, making it a flexible and scalable solution for building applications.

ReactJS components play a fundamental role in building modern web applications. They provide a modular and reusable approach to constructing user interfaces, improving code maintainability and promoting efficient development practices. With its virtual DOM and vast ecosystem of components, ReactJS empowers developers to create engaging and interactive applications with ease.

 Getting started with react – React JS Tutorial

Getting started with ReactJS is an exciting journey for developers looking to build dynamic and responsive user interfaces. To begin, it is essential to have a basic understanding of JavaScript and web development concepts. ReactJS utilizes a component-based architecture, making it crucial to grasp the concept of reusable UI elements.

The first step is to set up a ReactJS development environment, which involves installing Node.js and utilizing package managers like npm or Yarn. Once the environment is ready, creating a new React project can be done using tools like Create React App.

Understanding the core concepts of JSX, which combines JavaScript and HTML, is vital for building React components. React follows a unidirectional data flow, where data is passed from parent components to child components. It’s also important to familiarize yourself with React’s lifecycle methods and hooks, as they allow for managing state and performing side effects. With a solid foundation in ReactJS fundamentals, developers can explore the vast ecosystem of libraries, frameworks, and resources available to enhance their React development skills.

Introduction to React.js React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small, isolated pieces of code called “components,” as per React’s official website.

This represents the view part of the MVC framework. This is not a framework like AngularJS but just a library like jQuery. Many people get confused on this part and consider React as a framework instead of a library; this is wrong. It is a popular open-source JavaScript library that performs data viewing with the help of HTML.

Some people call it React JS or React.js, so don’t get confused. As it is developed by Facebook, it is also popularly known as “Facebook React.js.” Currently, it is maintained by Facebook and community developers who are interested in the library. It is also very efficient at updating the HTML document with new data, making it a perfect choice for data-driven web applications such as Facebook or Instagram.

History of ReactJS: Where did the name React in React.js come from? React JS Tutorial

The history of ReactJS can be traced back to 2011 when Facebook engineer Jordan Walke created an internal JavaScript library called “FaxJS.” It was initially used to enhance the performance and efficiency of Facebook’s news feed. Later, in 2013, Facebook released ReactJS as an open-source project, making it available to the wider developer community. ReactJS quickly gained popularity due to its unique approach to building user interfaces.

ReactJS was designed to address the challenge of building complex and interactive UIs with better performance and maintainability. It introduced the concept of components, allowing developers to break down the user interface into reusable and independent parts. This component-based architecture revolutionized the way developers approached front-end development, enabling them to build scalable and modular applications.

One of the key breakthroughs in ReactJS was the introduction of the virtual DOM (Document Object Model). With the virtual DOM, ReactJS is able to efficiently update and render only the necessary parts of the UI when changes occur, leading to improved performance compared to traditional rendering approaches. This innovation helped ReactJS gain recognition for its speed and efficiency in handling UI updates.

ReactJS continued to evolve rapidly, and in 2015, Facebook introduced React Native, a framework based on ReactJS that enables developers to build native mobile applications for iOS and Android platforms using JavaScript. This expansion into mobile development further cemented ReactJS as a versatile and powerful tool for building cross-platform applications.

Since its release, ReactJS has gained a vast and active community of developers who contribute to its growth. The React ecosystem has expanded to include various libraries, frameworks, and tools that complement ReactJS and enhance its capabilities. ReactJS has also been adopted by numerous tech giants and companies worldwide, solidifying its position as one of the leading choices for front-end development.

Where did the name “React” in Reactjs come from? – Based on the changes in the state of a component (the run-time value in the DOM), it re-renders the particular component automatically. I mean, it reacts to the changes in the DOM, so the name is React. For example, if you are displaying the customer details data in the page UI and, in run time, you have changed something in the customer data source (maybe in the customer table), then automatically those changes will be reflected in the browser without reloading or refreshing the page.

As mentioned earlier, React is just a UI part of MVC; we cannot implement a full-fledged web application just using React. For other models or controllers, we need to integrate another framework; this is one of the drawbacks of React.

React applications are based on components, so the heart of React is the component. In the coming section, we’ll discuss more components and other stuff for React.

ReactJS Tutorial: History of React and Benefits of React

What is the history of Reactjs and why should we use it?As we know, millions of people across the globe use Facebook, and a significant number of users increased when the mobile app revolution happened.

At that point in time, Facebook was facing a performance issue with its application. In this context, Facebook had begun to consider how it could improve the performance of its application.They began working on it, and it was finally released in 2011.

So, this is relatively new to the market when compared with other technologies on the market. Jordan Walke, a software engineer at Facebook, created the library. The first use case of React was in Facebook’s newsfeed in 2011.

Instagram later picks it up for use in their system.With time, React grew, and Facebook decided to make it open source in May 2013 at JSConf US. In 2015 at JSConf, React Native was announced, which enabled easy Android and iOS development.

In the same year, React Native was open-sourced to help it grow. So we understood the history and purpose of React—it’s mainly to speed up the application performance or dynamic page load time. ReactJS uses a virtual DOM to speed up the rendering process.

React JS Tutorial: What are the prerequisites for learning React.js?

What are the prerequisites for learning React.js? When it comes to prerequisites for developer prior experience, before coming to React learning, the developer should have a fair knowledge or understanding of JavaScript and HTML.

And the prerequisites for the React development tool determine whether we develop using an online tool or editor or a local development environment in two ways.

If you opt to develop through an online editor, there is no need to install anything on your local machine. Below is one of the online React development editors.

For the development of React on your local machine, you need to install the following software:

  1.  Node.js and NPM – install the Node.js from this link.
  2.  Visual Studio code – There are plenty of IDE, one of the popular ones in the Visual Studio Code. You can download it from here.

Notes

  • While installing the Node.js from the above link you can choose the below version.

 

Node js download - download for Windows (x64)
Node.js – download for Windows (x64)
  • The Node.js 10.16.0 version works fine with the new application that you will create, but if you download any GitHub React project, in most cases, this will not work. When you run the NPM start command, you will receive the version mismatch error, which expects a lower version number than 10.x. The exact error message is as follows:

“Your dev environment is running NodeJs version v10.13.x which does not meet the requirements for running this tool. This tool requires a version of NodeJS that matches >= 8.9.4 <9.0.0”

Your dev environment is running NodeJs version v10.13.x which does not meet the requirements for running this tool. This tool requires a version of NodeJS that matches >= 8.9.4 <9.0.0
Your dev environment is running NodeJs version v10.13.x which does not meet the requirements for running this tool. This tool requires a version of NodeJS that matches >= 8.9.4 <9.0.0

If you face this issue, don’t panic, just follow the below link, here you need to downgrade the node.js using the NVM tool(NVM tool can be downloaded from here.

For complete instructions to downgrade, please click here.

Reactjs components – React JS Tutorial

ReactJS components are the building blocks of user interfaces in ReactJS applications. They encapsulate specific functionality and user interface elements, allowing developers to create modular, reusable, and manageable code structures. A ReactJS component represents a self-contained piece of the user interface, which can be composed and combined with other components to create complex UIs.

ReactJS components can be classified into two main types: functional components and class components. Functional components are JavaScript functions that receive input data, known as props, and return UI elements. They are simple, stateless, and primarily focused on rendering UI based on the provided props. Functional components are easy to understand, test, and maintain, making them the preferred choice for simpler UI elements.

On the other hand, class components are ES6 classes that extend the React.Component class. They have additional features like local state and lifecycle methods. Class components are suitable for more complex UI elements that require state management, event handling, or interaction with external data sources. However, with the introduction of React Hooks in newer versions of React, functional components can also handle state and lifecycle functionality, reducing the need for class components in many cases.

ReactJS components operate based on the concept of unidirectional data flow. Data flows from parent components to child components through props, ensuring that changes in one component don’t affect other components unless explicitly passed down. This architectural pattern promotes code reusability and maintainability since components can be developed independently and composed together in various combinations.

ReactJS components also introduce the concept of a virtual DOM (Document Object Model), which is a lightweight, in-memory representation of the actual browser DOM. When changes occur in a ReactJS component, the virtual DOM efficiently calculates the minimal set of updates needed to synchronize the actual browser DOM, minimizing unnecessary re-renders and optimizing performance.

Furthermore, ReactJS components promote reusability by allowing developers to define their own custom components and leverage existing libraries of pre-built components. This modularity simplifies development, as components can be reused across different projects or even shared within the React community.

Understanding React.js Components As we pointed out in the introduction section, components are the heart of React JS; now we’ll see them in detail. As far as components are concerned in React, they have the following characteristics:

  • React Component is a reusable piece of code that includes HTML and Javascript.
  • Component data will be stored in the component’s state.
  • This state can be modified based on user action or other actions.
  • When a component state is changed, React will re-render the component to the browser.
  • We must implement a render method when creating a component.

Let’s take the example of a typical website home page. This will have left navigation, top navigation, a header, a footer, and the actual content.

In a traditional HTML or Asp.net application, we’ll develop this using some sort of left/right, header, footer, or some sort of section or panel controls, but in reacting to each section of the page, we need to develop a separate component. For the said scenario, we need to have left navigation, top navigation, header, footer, and an actual content “component,” respectively.

A component can pass the data from parent to child through the props and state (in the coming section, we’ll discuss more about the props and state).

Keytake-away:

ReactJS components are the core building blocks of user interfaces in ReactJS applications. They enable developers to create modular, reusable, and manageable code structures by encapsulating functionality and user interface elements. With their focus on reusability, data flow, and virtual DOM, ReactJS components provide an efficient and scalable approach to building interactive and dynamic web applications.

ReactJS Components: A Real-Time Example of a Component Any Website Home Page (React JS Tutorial)

Below are the example of the ReactJS components:

Site Home Page

Reactjs components - a real-time example of React JS component
A real-time example of React JS component

Social Media Application

Imagine you are building a social media application that displays posts and allows users to like or comment on those posts. We can break down this application into several ReactJS components to handle different functionalities and UI elements.

Post Component:

The Post component represents an individual post with its content, likes count, and comments. It receives props like the post content, number of likes, and comments data. It renders the post content, displays the number of likes and comments, and provides a button to handle liking the post. The Post component can be reusable, allowing it to be used to display multiple posts.

LikeButton Component:

The LikeButton component is responsible for handling the logic and UI of the like button within each post. It receives props such as the initial like status (liked or not liked) and the current number of likes. It provides an interactive button that users can click to toggle the like status of the post and updates the number of likes accordingly.

CommentSection Component:

The CommentSection component manages the display and submission of comments for each post. It receives props containing the comments data and renders a list of comments. It provides an input field and submit button for users to add new comments. When a comment is submitted, it updates the comments data and triggers a re-render of the CommentSection component.

These are just a few examples of ReactJS components in a social media application. By breaking down the UI into smaller reusable components, you can efficiently manage and update different parts of the application independently, improving code organization and reusability.

ReactJS components allow you to create a modular and scalable architecture for your application, making it easier to build interactive and dynamic user interfaces.

ReactJS Components: React Component Types (React JS Tutorial)

React Component Types: In core react.js, this is classified as follows based on how we write and render the component:

  1. Functional
  2. Class
  3. Container
React class component - Types of the component
Types of the component in React JS

In ReactJS, there are two main types of components: functional components and class components. Let’s explore each of them in detail:

Functional Components:

Functional components are JavaScript functions that receive input data, known as props, and return UI elements. They are also referred to as stateless components since they do not have their own internal state. Functional components are simple, lightweight, and primarily focused on rendering UI based on the provided props. They are easy to understand, test, and maintain, making them a preferred choice for simpler UI elements. With the introduction of React Hooks in newer versions of React, functional components can also handle state and lifecycle functionality through the use of hooks like useState and useEffect.

Here’s an example of a functional component in ReactJS:

import React from 'react';

const MyFunctionalComponent = (props) => {
return <div>{props.message}</div>;
};

export default MyFunctionalComponent;

Class Components:

Class components are ES6 classes that extend the React.Component class. They have additional features like local state and lifecycle methods. Class components were the traditional way of creating components in React before the introduction of functional components with hooks. They are suitable for more complex UI elements that require state management, event handling, or interaction with external data sources.

Here’s an example of a class component in ReactJS:

import React, { Component } from 'react';

class MyClassComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}

handleClick = () => {
this.setState({ count: this.state.count + 1 });
};

render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
<p>Count: {this.state.count}</p>
</div>
);
}
}

export default MyClassComponent;

It’s worth noting that with the introduction of React Hooks, functional components with hooks have become the preferred approach for most use cases. They offer a simpler and more concise way to handle state and lifecycle functionality. However, class components are still relevant and necessary in certain scenarios, especially when working with older codebases or integrating with third-party libraries that rely on class components.

Both functional components and class components play a vital role in building ReactJS applications, and developers can choose the appropriate type based on the complexity and requirements of their UI elements.

React Lifecycle: React Life Cycle Methods (Diagram)

React lifecycle methods are special methods that are automatically invoked at different stages of a component’s lifecycle. These methods allow developers to control and perform specific actions during different phases of a component’s existence, such as initialization, updating, and unmounting.

In React versions before 16.3, there were three main categories of lifecycle methods: mounting, updating, and unmounting. However, with the introduction of React Hooks, the class-based lifecycle methods are no longer recommended, and functional components can use hooks like useEffect to achieve similar functionality.

Here is an overview of the traditional React lifecycle methods:

Mounting Phase:

  • constructor(): The constructor is called when a component is being initialized. It is primarily used to initialize state and bind event handlers.
  • componentWillMount(): This method is invoked just before a component is rendered for the first time. It is not commonly used and is considered legacy.
  • render(): The render method is responsible for generating the JSX that represents the component’s UI. It must return valid JSX.
  • componentDidMount(): This method is called after the component has been rendered for the first time and added to the DOM. It is commonly used for initialization tasks, such as fetching data from an API or setting up event listeners.

Updating Phase:

  • componentWillReceiveProps(nextProps): This method is triggered when the component is about to receive new props. It is not recommended for use and is considered legacy.
  • shouldComponentUpdate(nextProps, nextState): This method is called before a component is re-rendered. It allows you to control whether the component should update or not based on changes in props or state. By default, it returns true.
  • componentWillUpdate(nextProps, nextState): This method is invoked just before a component is updated and re-rendered. It is not commonly used and is considered legacy.
  • render(): The render method is called again to re-render the component with any updated props or state.
  • componentDidUpdate(prevProps, prevState): This method is called after the component has been re-rendered. It is commonly used to perform side effects, such as updating the DOM or making additional API calls based on changes.

Unmounting Phase:

  • componentWillUnmount(): This method is called just before a component is removed from the DOM. It is used to perform cleanup tasks, such as removing event listeners or cancelling subscriptions.

It’s important to note that in React versions 16.3 and later, several of these lifecycle methods have been deprecated and replaced with new methods. React Hooks, such as useEffect, useState, and useContext, provide a more flexible and concise way to handle state and lifecycle functionality in functional components.

React lifecycle methods allow developers to control the behavior of components during different stages of their existence. While the class-based lifecycle methods are still valid, the use of hooks in functional components is now the recommended approach. These methods provide opportunities for initialization, rendering, updating, and cleanup, enabling developers to manage and manipulate components based on their lifecycle needs.

React Life Cycle Methods (Diagram)

React provides the developers with a set of predefined functions that, if present, are invoked around specific events in the lifetime of the component. Developers are expected to override the functions with desired logic for them to execute properly. I have illustrated this list in the below diagram.

Reactjs components - Component life cycle methods
Component life cycle methods in React JS (Initialization, Mounting, Updation, Un-mounting)

Notes:

  • In the above, whichever method ends with “will,” i.e. before the render method call,
  • In the above, whichever method ends with “Did,” i.e., after the render method call,
  • As shown above, the React component lifecycle has three categories: mounting, updating, and unmounting.
  • As shown above, render() is the most commonly used life-cycle method.
  • As shown above, componentDidMount() happens as soon as your component is mounted.
  • As shown above, componentDidUpdate() happens as soon as the updating happens.
  • I’ll explain each type of method, for example, in a separate article.

Summary: React JS Tutorial (ReactJS Components)

This tutorial on ReactJS components provides a comprehensive understanding of the fundamental building blocks in ReactJS applications. It highlights the significance of breaking down the user interface into reusable and modular components. By explaining the two main types of components, functional components and class components, the tutorial demonstrates how to create UI elements and handle complex functionalities. Additionally, it emphasizes the unidirectional data flow and the role of the virtual DOM in ReactJS. The tutorial also showcases the benefits of using ReactJS components, such as code reusability, maintainability, and performance optimization. Overall, this tutorial equips developers with the knowledge to effectively utilize ReactJS components to build dynamic and interactive web applications.

So, as part of Part 1, we learned the following fundamentals for getting started with React JS:

  • Introduction to React
  • What is the name of React?
  • History, and why react?
  • Prerequisites of the React project.
  • The component in React JS.
  • A real-time example of a component is any website’s home page.
  • What are the types of components in React?
  • React Component lifecycle methods (diagram)
  • React life-cycle methods diagram

References – React JS Tutorial

See Also: SharePoint Online Tutorial

You may also like the below SharePoint Online tutorials:

Buy the premium version of SharePoint Online & Office 365 administration eBook from here:


Buy SharePoint Online & Office 365 Administration eBook

 

About Post Author

Do you have a better solution or question on this topic? Please leave a comment