React Component

React components are the fundamental building blocks of a React application. They encapsulate parts of the user interface, making it easy to create complex UIs from smaller, isolated pieces of code. Components can be either functional or class-based, and they can manage their own state and lifecycle methods. Here’s an in-depth look at React components:

Types of Components
  1. Functional Components
  2. Class Components

Functional Components

Functional components are simpler and are typically used for components that don’t need to manage state or lifecycle methods. They are just JavaScript functions that accept props as an argument and return React elements.

Example of a functional component:


//src/MyComponent.js
import React from 'react';

function Welcome() {
  return 

Hello World!

; } export default Welcome;

In this example, Welcome is a functional component and returns a React element.

Class Components

Class components are more feature-rich. They allow you to use additional features like local state and lifecycle methods. Class components extend React.Component.

Example of a class component:


src/Greetings.js
import React, { Component } from 'react';

class Greetings extends React.Component {
  render() {
    return 

Hello World!

; } } export default Greetings;

In this example, Greetings is a class component that renders the same output as the functional component.

Rendering a component

Rendering a component in React.js involves creating a component and then rendering it in the DOM.

Import and use the component in your main application file (src/App.js).

Rendering a function component

// src/App.js
import React from 'react';
import MyComponent from './MyComponent';

const App = () => {
  return (
    <div>
       <MyComponent />
     </div>
  );
};

export default App;

In this example, output will be Hello World!

Rendering a class component

It will be same as a function component


// src/App.js
import React from 'react';
import Greetings from './Greetings';

const App = () => {
  return (
    <div>
      <Greetings />
    </div>
  );
};

export default App;

In this example, output will be Hello World!