What are Components in ReactJS

As we already know, React is a JavaScript library for building User Interfaces. Yes, We can build a User Interface with HTML, CSS, and vanilla JavaScript as well. But React makes it simpler to create User Interfaces and make them more interactive. To make the process easy to use and more dynamic, React provides a concept called Components. 

What is a Component in ReactJS?

In ReactJS, a component represents a part of the User Interface. They are like functions in JavaScript and they return elements that describe what should be shown on the viewport. We can pass data from one Component to another with arbitrary inputs (props).

Example of React Component?

  • Define a component in reactJS

Step 1:  Let’s start from the core. First, we will open our ReactJS app in Visual Studio Code. Then we will create a folder inside src. Click the right mouse button on src and then select New Folder. And we will name this folder “Components”. Here, we will create every other Component as needed. After naming it, hit enter and the folder named Components will be created inside src. 

Step 2: After that, we will create a Component inside the Components folder. Just right-click on the Components folder then click on New File.

you can name your Component as you like. But it is recommended to name a Component after its role. For example, if we want to create a Headers Component, we should name it Headers.js or Navbar.js. Like this. Let’s just create a Component named, Home.js.

Make sure the first character of the Component’s name is in Capital Letter. It is suggested that we follow CammelCase order to create a Component or function in ReactJS.

After naming the Component, hit enter. And the new file will be created. That’s how we can create a Component. But to make it functional we have to follow a few more steps.

Step 3: Inside of Home Component (Home.js),  first we have to import React.

//we have to import React from 'react' to make this Component functional.
import React from 'react';

Then we will create an arrow function and the function name will be the same as the Component’s Name (Home). It doesn’t necessarily have to be an arrow function. We can create with a regular function as well.

import React from 'react';

const Home = () => {
   
};

After creating the function, we will return a <div>…</div> in the inside of that function.

import React from 'react';

const Home = () => {
    return (
        <div>
// we can write anything here
        </div>
    );
};

That’s how we can create a Component in ReactJS.

  • Call  and use the component in reactJS

The idea of Component came from the functional approach of vanilla JavaScript. Where, after creating a function we have to call that function to use. We have to do that for Components as well. But before importing a Component, first, we have to export the Component we want to use. We can just simply write export default Home at the bottom of the Component.

import React from 'react';

const Home = () => {
    return (
        <div>

        </div>
    );
};

export default Home; //it will export this Component so that we can import it and use it from another Component

Now let’s go to the App.js file and import this Home Component to use it there. Whatever we write in App.js  file it will be visible in our browser. Without importing a Component directly or indirectly in App.js file, we won’t be able to see any changes.

Our App.js file should look like this. And we will remove the <header> tag from here.

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
// we will remove header from here
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

After removing <header>, we will import Home.js at the top of the App function.

import logo from './logo.svg';
import './App.css';

//we will import the component here

function App() {
  return (
    <div className="App">
      // we will call the component here
    </div>
  );
}

export default App;

After importing the Component,

import logo from './logo.svg';
import './App.css';

//import the component here
import Home from './Components/Home';

function App() {
  return (
    <div className="App">
      
    </div>
  );
}

export default App;

Now we just have to call the Component inside of <div>...</div> tag to be used.

import logo from './logo.svg';
import './App.css';
// importing Home component from file path
import Home from './Components/Home';

function App() {
  return (
    <div className="App">
      // you can call a Component like this
      <Home />
    </div>
  );
}

export default App;

 

That’s how you can create, export, import, and use a Component. Just keep in mind a few things,

  • Use Capital Letter and Cammal Case to name the Component.
  • Make sure you exported it correctly.
  • Import the Component you want to use from the proper file path.
  • Make sure to call it properly.

Why is React all about Components?

All User Interfaces are made up of Components in ReactJs. Let’s take a look at the screenshot of Netflix’s interface down below,

As we can see, there are a couple of building blocks that make up this interface. If we look carefully, the structure of the blocks (marked as red rectangular) is pretty much similar. But the contents inside the blocks are different. It’s the same item with different data. And this is exactly what Components are.

Similar in look, different in data

Building blocks, that can be reused in User Interface. A Component is made up of some HTML code, some CSS for styling, and JavaScript code for logic.  We don’t have to reuse a Component to make it a Component. It, itself is reusable. Reusability is one of its nature.

There can be more Components in User Interface. A Navigation Bar can be a Component, A Table can be a Component, A Footer can be a Component, the contents inside of a table can be a Component, and even the overall interface can be a Component as well.

To make it simpler, each individual block that is inside of another block and the parent block itself can be a Component.

We build these individual Components, and then we tell React – how to compose them together; hence the final product can be shown in the User Interface.

Why do we use Components in ReactJs?

React embraces this idea of Component for the “Reusability aspect” and “Separating the Concerns”.

We can create a Component and reuse it wherever we need and we can use the component as much as we want.  With Component’s reusability, for the similar look and structure in User Interface, we don’t have to write the code again and again.

Now, we don’t have to repeat the codes multiple times, It increases the readability of the codes. And we can keep our code base small and manageable.

Instead of having a large file that holds all the HTML codes and the JavaScript logic for the entire User Interface we now have small separate blocks or units (Components) where every Component has one clear concern, one specific thing to manage in User Interface.

And if we split the codes across multiple files,  then we will have small pieces of codes that can be easily manageable and maintainable but work together to build the User Interface.

If we look at vanilla JavaScript, we declare a function with parameter(s) and we can reuse that function by passing different promises and can get different outputs that depend on the promise.

React just picked up the concept of functions and separated the codes across the function and translates it to the front-end application world. Where we build an entire User Interface by separating our codes into multiple Components which we can use as our needs.

Type of Components in ReactJS?

There are two types of Components in ReactJS. Functional Components and Class Components.

Functional Components:
import logo from './logo.svg';
import './App.css';

//this is a function that returns something.
function App() {
  return (
    <div className="App">
      <h2>This is a functional Component</h2>
    </div>
  );
}

export default App;

If we take a look at the above code snippet, this is a Functional Component, that returns something. It is pretty easy to write. The function will have some input and some output. The input would be the props and the output would be whatever is being returned from the function. As we can see, App is a function and it does some logic and it has some UI rendering logic. After that it outputs something.

One major difference between Functional and Class Component is setting up the state. 

import logo from './logo.svg';
import './App.css';
import { useState } from 'react';

function App() {
//states
  const [name, setName] = useState('name');
  const [age, setAge] = useState(25);
  return (
    <div className="App">
      <h2>My name is {name}</h2>
      <h2>My age {age}</h2>
    </div>
  );
}

export default App;

We can take a look at the above code snippet. And here we can see two pieces of state. We have initialized the useState() hook and we have each individual variable (name, age) with its own set function. And each one has a default value inside useState() hook given at the start. And to use these variables, as you can see we just have to call the variables dynamically inside the HTML tag.

Class Components: 

If we want to write the same component from above, but in the Class base Component, it gets a little bit more tricky.

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div>
        <h2>This is a Class Component</h2>
      </div>
    );
  }
}

export default App;

But we will get the same output for the both Class and Functional Component. At the very first of a Class Component, we can see the function starts with class . This is why in fact it is a Class Component. In a Functional Component, we can simply return JSX. But in a Class based Component, we actually need a render function that then has the ability to return the JSX.  And this is gonna run with every re-render.

To set up the state,

import React, { Component } from 'react';

class App extends Component {
  constructor(props){
    super(props);

    this.state={
      name: "",
      age: 26
    }
  }
  render() {
    return (
      <div>
        <h2>My name is {this.state.name}</h2>
        <h2>My age {this.state.age}</h2>
      </div>
    );
  }
}

export default App;

In Class Component, if we want to make use of state then we actually have to prepare the state in advance. And we do this inside of the constructor, which is why we initialize the class itself. So in this case, we have a constructor which takes props as its argument. And as you can see we pass a massive object inside this.state . And when we want to consume this, we have to apply a different approach than Functional Components. We have to say this.state.variable_name.