React Components

React Components

Components in React are the way to group the independent code and make them reusable in different parts of the program. Before Understanding the React components in depth. Let’s first understand React.

What is React?

React is an open-source  JavaScript library that helps in building the user interface. React is not responsible for other parts of the application like routing.  It is mainly focused on building rich user interfaces. But what exactly does that mean?  Consider an example netflix.com.

It runs very smoothly. And it performs operations exactly like a mobile application in which we can have Responsive Design, Quick and Fast Response User Interaction, Nice Transition, don’t need to wait for loading the content, etc.

In that, if we go to any page then the transition happens very nicely and smoothly like in mobile applications.  That User experience can be achieved using the help of React

If we look at traditional websites, They don’t have that much User Interaction. On that web pages, you click on a link and wait for a new page to load. And that makes it slower each time fetching the web page. The Operations on the traditional websites perform like-

The above image states that when you visit any website the server responds to the web page and that webpage is interpreted by the browser and displayed. So each time we request another web page of the same website then again the request will go to the server,  And the server will respond to a new webpage. 

Similarly, you click on a button and wait for the action to be computed by the server. And the server has latency where the data (web page) loaded from the server is interpreted and displayed on the browser.

So this request and response cycle for loading an HTML page every time can be reduced with the help of JavaScript.

JavaScript is a high-level, interpreted, programming language used to make web pages more interactive. It allows the implementation of complex and beautiful things/designs on web pages.

The Javascript on the user side runs on the browser after successfully loading the web page. It can do this by just manipulating the DOM(Document Object Model)  elements that are rendered on the screen. Javascript allows us to change the HTML page that we need to display without fetching a new HTML page from the server.

And that’s what React does with the web pages. React has something react-dom that helps to manipulate the web pages, without each time asking the server to send the HTML page.

So, React is nothing but the client-side JavaScript library that is used for building modern reactive user interfaces. React gives us modern high-level, rich syntax that helps to build interactive web pages. It moreover focuses on the declarative and component-focused approach.

Why Learn React? 

React is an open-source library developed by Facebook. That has more than 100k stars on GitHub and it has a huge developer community. That means almost every problem that can be encountered while building the react application has a solution that most probably has been already present. The most important feature of React is that it is component-based. And these components together help to make a large application. React is used to make a single-page application. And it is declarative, which means we only need to tell the React what to do. And How to do that is managed by the react library UI. In which there is a React Algorithm called react-dom that does it for us.

Then how is React different from Simple Javascript?

Let’s understand this with the help of an example. In the below figure, consider the sample web application is made using vanilla javascript. And it has some bunch of javascript code that makes this simple application.

HTML Code –

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Just JavaScript</title>
    <link rel="stylesheet" href="style.css">
    <script src="app.js" defer></script>
</head>

<body>
    <h1>My Todos</h1>
    <div class="card">
        <h2>Learn React</h2>
        <div class="actions">
            <button class="btn">Delete</button>
        </div>
    </div>
</body>

</html>

CSS Code –

* {  
    box-sizing: border-box;
}
  
body {
    font-family: sans-serif;  
    margin: 3rem;
    background-color:#dfdfdf;    
}
   
h1, h2{    
    color: #333333;
}
     
.btn {    
    font: inherit;
    padding: 0.5rem 1.5rem;
    cursor: pointer;
    border-radius: 4px;
    background-color: #800040;
    color: white;
    border: 1px solid #800040;
    margin: 0 1rem;
}

.btn:hover {  
    background-color: #9c1458;
    border-color: #9c1458;
}  
.btn--alt {
       
    background-color: transparent;
    color: #800040;
}

.btn--alt:hover {    
    background-color: #f8dae9;
}

.card {
    background-color: white;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
    padding: 1rem;
    width: 20rem;
    z-index: -100;
}

.actions {
    text-align: right;
}
   
.modal {    
    box-shadow: 0 1px 4px rgba (0, 0, 0, 0.2);
    border-radius: 6px;
    background-color: white;
    padding: 1rem;
    text-align: center;
    width: 30rem;
    margin: 0 auto;
    float: none;
    z-index: 20;
}
.backdrop {
    opacity:0.8;
    background-color:rgb(88, 85, 85);
    position:fixed;
    width:100%;
    height:100%;
    top:0px;
    left:0px;
    z-index: -1;
}

JavaScript Code –

const button = document.querySelector("button");
let modal;
let backdrop;
button.addEventListener('click', showModalHandler);

function showModalHandler() {
    if (modal) {
        return;
    }
    modal = document.createElement('div');
    modal.className = 'modal';
    const modalText = document.createElement('p');
    modalText.textContent = 'Are you sure?';
    const modalCancelAction = document.createElement("button");
    modalCancelAction.textContent = "Cancel";
    modalCancelAction.className = "btn btn-alt";
    modalCancelAction.addEventListener('click', closeModalHandler);
    const modalConfirmAction = document.createElement('button');
    modalConfirmAction.textContent = 'Confirm';
    modalConfirmAction.className = 'btn';
    modalConfirmAction.addEventListener('click', closeModalHandler);
    modal.append(modalText);
    modal.append(modalCancelAction);
    modal.append(modalConfirmAction);
    backdrop = document.createElement('div');
    backdrop.className = 'backdrop';
    backdrop.addEventListener('click', closeModalHandler);
    document.body.append(backdrop);
    document.body.append(modal);
}

function closeModalHandler() {
    modal.remove();
    modal = null;
    backdrop.remove();
    backdrop = null;
}

Explanation –

In the above line of codes and screenshot related to the code. We have a Card That contains a delete button. And on clicking that button we get the popup confirming whether we want to delete the to-do list or not. 

In the JavaScript file, we have written a bunch of code to delete the to-do list and also for confirmation messages.

Now, We have only one to-do list. So for this to-do list, we have a bunch of HTML codes as well as some JavaScript code that helps to render it on the page. 

Consider a scenario when we have multiple to-do lists, and we want to render it on the screen then the whole HTML code, as well as the JavaScript code, will also be increased. And also that with just JavaScript we have to write every single step that should be taken to handle any action. We have to follow imperative action. And this way of programming is called the imperative approach in which each step should be sequentially defined.

Example – Fetching some data from the database and adding it to the to-do list then rendering it to the page will cause more Complex and lengthier code. 

So exactly this problem has been solved using the React Components. React is all about splitting the whole application into small building blocks, that is called components. The components of React will help to avoid rewriting the code. Instead, that particular thing will be made up of the component. And anywhere in the application, that component is required, then it can be Embedded as a custom tag in the react application.

Using React – 

In react we define the contents in the term of components. And in an application, there can be thousands of components that together help to build a complete system.

So as per our example. The below snippet of React code is only responsible for rendering the to-do list on the page.

Main React App.js Code –

import React from 'React';
import Todo from './components/Todo';
function App() {
    return (
        <div>
            <h1>My Todos</h1>
            <Todo text='Learn React' />
        </div>
    );
}
export default App;

In the above code, the Todo is the component that is defined on the separate file as a component. And as many times we require it to use on the application then we can embed it with just  <Todo text = ‘Learn React’ />. And the snippets of the Todo Component is defined as the snippet of –

Todo Component Code –

import { useState } from 'react';
import Backdrop from './Backdrop';
import Modal from './Modal';

function Todo(props) {
    const [showModal, setShowModal] = useState

    function showModalHandler() {
        setShowModal(true);
    }
    function closeModalHandler() {
        setShowModal(false);
    }
    return (
        <div className='card'>
            <h2>{props.text}</h2>
            <div className='actions'>
                <button className='btn' onClick={showModalHandler}>
                    Delete
                </button>
            </div>
            {showModal && <Backdrop onClick={closeModalHandler} />}
            {showModal && <Modal text='Are you sure?' onClose={closeModalHandler} />}
        </div>
    );
}
export default Todo;

The above snippet of code of the component todo will generate todo and this is being rendered by the react-dom on the application.

Components of React

In React, components are part of the User Interface. And React is all about components. Components are the small encapsulated building blocks of the application and these components are nothing but the part of the application that has its individual functions and these can be merged together for making a large application.

For Example – Consider the traditional website in which it contains the different parts of the application such as – 

  1. Header.
  2. Footer.
  3. Main Content.
  4. Side Navbar.
  5. The main component contains this whole component.

Each section can be considered a component. And these components can together build a complete application.
Components can also make it possible to write reusable code. As we have discussed earlier in this blog. And also if we write a component of some data on React, then the same components  we can use with the other library like Angular and Vue, passing the right data value on the component.

For large enterprise applications, the ability to reuse code is a huge plus point. For understanding this much better, let’s take the example of the Facebook feed page.

In the above image of the Facebook feed page, all the components are marked with the arrow – 

  • The Navbar is a component that also contains sub-component such as (search icon, notification icon, grid view icon, etc).
  • The sidebar is also a component that displays the basic details of the users.
  • Feed post is also a component that helps to post a feed. And other view feeds also have a different component in them.
  • User Status view card is also a component, etc. There would be more components rather than listed here.

These are all the basic building blocks (components) of the Facebook page that together make a complete Facebook application.

The reusability of the components in this example can be the status card that displays the user status. And that status component can be written once and will be applied to call as many times in the application. If we do this with simple javascript, HTML, and CSS, then the codebase will be very large and it will be difficult to manage. But with the help of components, it is very easy to implement and use it wherever it wants.

Why Use Components?

  1. Reusability – Helps in keeping our codebase as small and manageable.
  2. Separation and concerns – Instead of having a single large file, we have all separate units. Where each unit (component) has one clear task, that the main logic focuses on. So these small pieces of code are easy to manage and maintain.
  3. Custom Tag – React components also helps to define the custom tags that are embedded with the component and it increases the code readability.

How Exactly is a Component Built?

In the end, the User Interface is all about HTML + CSS + JAVASCRIPT. And React components are all about combining this into the unit as per requirement and then combining these different components into one to make a complete Application.

The component in Code – 
Component translates code into the application. The components are placed in a separate JavaScript file that can be either .JSX file or simple .JS file.

JSX is a React continuation to the JavaScript style syntax that provides a way to structure component rendering using syntax familiar to many developers. And on the other hand, a JS file is a simple javascript file extension.

React Components are placed in either of these 2 files. And these codes are simple javascript code with some extensions to others like HTML. 

Now does the code look like in the component? That all depends on the type of the component.

Type of Components in React

  1. Stateless Functional Components.
  2. Stateful Class Components.

Stateless Functional Component

Functional Components are just javascript functions. It can just receive the properties (that is often called props) and return the HTML(JSX) that describes the UI.

Creating functional components –

  • Create a new file name with <component-name>.jsx extension.
  • Write a function that is returning some HTML. In our case, let’s consider a function returning the message – “Hello <name>! Welcome to InterviewBit”. So the function code looks like this-
import React from 'react';
function Message(props){
    return <p>Hello {props.text}! Welcome to InterviewBit.</p>;
}
export default Message;
  • Now in the main React App.js import this Message. And render it, as per requirement. So in App.js, the code will be imported as –
import React from 'React';
	import Message from './components/Message';
	function App() {
    	return (
         <div>
           	<Message text='Yash' />
         </div>
    	   );
	}
	export default App;

After executing this component, the applications should display the content on the page as –  Hello Yash! Welcome to InterviewBit.

Explanation –  In the function Message that receives the property (props) and that props are used to append the text from the prop and concatenate with the message and exports that. And on the other end, in the main App.js, It is imported and called by giving the props, and the returned message is rendered on the application as many times as required.

We have used the default keyword in the export statement in the Message component. But what does that mean?  Actually, using the default keyword allows using of the custom tag name in the imported file. Like w have used  <Message text = “Yash”/>

So instead of Message, we can use any custom tag in this place if the component is exported with the default keyword. The only thing to handle is, during the import statement we need to specify our custom tag. Like- 

import MyCustomTag from ‘./components/Message’;

Note- All React Components are advised to be put in the components folder as per React. Because this makes the code more organized and manageable.

Stateless Class Component

Class Component is basically ES6 (Ecmascript 2015) Classes. Just like the functional component class component also optionally receives props as input and returns the HTML (JSX) as output. And other than this feature, the class component can also maintain a private internal state. 

In simpler words, a class component can maintain some information that is private to that component. And use that information to describe the user interface.

Creating the Class Component –  

  • Create a new file name with <component-name>.jsx extension.
  • Whenever we are making a class component, then we need to import the Component class from React library. So we need to import that. And then create a class of the component you wish to create by extending the component class. Then create a render method with the logic you wish to return.
import React, { Component } from 'react';
class Message extends Component{
    render(props){
        return <p>Hello {props.text}! Welcome to InterviewBit.</p>;
    }
}
export default Message;
  • Now the class component needs to be imported wherever want in the application to be used. Let’s embed this in the main App.js file.
import React from 'React';
	import Message from './components/Message';
	function App() {
    	    return (
        	<div>
                <Message text='Yash' />
        	</div>
    	    );
	}
	export default App;

After executing this, the output will be the same as our functional component. That is – Hello Yash! Welcome to InterviewBit.

Explanation – We have imported the Component class from the react library. But what was that?  Actually, the Component has a render method that needs to be overridden in the custom component class to return the HTML ( JSX ) data.  And the default keyword works exactly as we learned in the functional component.

Functional Components vs Class Components 

Functional ComponentsClass Components
1. It is a simple function.1. It has a bit more feature-rich.
2. We should try to use functional components as much as possible. Because it has faster execution. And also have some advantages such as – 

(a) Absence of ‘this’ keyword. Because this can be wide tricky to handle.
(b) Solution without using states. That helps to debug applications easier. 
2. This can maintain its own private data usually called as states. This can contain complicated UI logic. So that’s why if there is no large work, then it is not recommended to use in the application. It also provides the feature of React life cycle hooks.
3. Functional components don’t contain much complex implementation. That’s why it is also called – stateless/dumb/presentational component.3. Because of this bunch of functions available, It is also called stateful/smart/container component. 

Note- Class components are on the depreciation path. The react team and community suggest the use of Functional components. The Class components functionality is augmented in Functional Components through React Hooks.

Conclusion

React is the open-source javascript library used for building front-end User Interfaces. It is based on the components themselves and that makes the development much easier. And as well as the code maintainability will increase. With the help of components, the code snippets can be reused on the different parts of the application wherever it is required.

Additional Resources

Previous Post

8 Nmap Commands That You Should Know About

Next Post

Components of Data Warehouse