Saturday, February 13, 2021

React Components

Components are the building blocks of any React app and a typical React app will have many of these. Simply put, a component is a JavaScript class or function that optionally accepts inputs i.e., properties(props) and returns a React element that describes how a section of the UI (User Interface) should appear.

Every React component have their own structure, methods as well as APIs. They can be reusable as per your need. For better understanding, consider the entire UI as a tree. Here, the root is the starting component, and each of the other pieces becomes branches, which are further divided into sub-branches.

In ReactJS, we have mainly two types of components. They are

  1. Functional Components
  2. Class Components

 

Function Component

A function component is the simplest form of a React component. It is a simple function with a simple syntax.

MyComponent1.js

import React from "react";

function MyComponent1(props) {

  return <h1>This is Function Component </h1>;

}

export default MyComponent1;

 

We have created a function called MyComponent1 that returned h1 tag as shown above. The name of the function acts as an element, as shown below:

The Component MyComponent1 is used as an Html tag, i.e., < MyComponent1 /> and same is exported using export.

Let us now use this component in index.js file as shown below:

app.js

import MyComponent1 from "./MyComponent1";

function App() {

  return (

    <div className="App">

      <MyComponent1 />

    </div>

  );

}

export default App;

Here is the output in the browser:


Class as Component

Class components are more complex than functional components. It requires you to extend from React. Component and create a render function which returns a React element. Here is a ReactJS example that uses a class as a component.

MyComponent2.js

import React from "react";

class MyComponent2 extends React.Component {

  render() {

    return <h1>This is Class Component </h1>;

  }

}

export default MyComponent2;


The Component MyComponent2 is used as an Html tag, i.e., < MyComponent2 /> and same is exported using export. We can use MyComponent2 component in App.js file as follows:

App.js

import MyComponent1 from "./MyComponent1";

import MyComponent2 from "./MyComponent2";

function App() {

  return (

    <div className="App">

      <MyComponent1 />

      <MyComponent2 />

    </div>

  );

}

export default App;

The Component MyComponent2 is used as an Html tag i.e., < MyComponent2 /> 

Here is the output of the same.