A Component is one of the core building blocks or small portion of code in React application. For the development of a single page application, the developers wrote hundreds of lines of code. Making updates to these programmes, which use the traditional DOM structure, proved exceedingly difficult. If a mistake is discovered, the entire programme is manually searched and updated. Using components makes creating user interfaces much easy. You may view a user interface (UI) divided into several separate parts, or components, and work on them individually before merging them all into a parent component to create your final UI.
As you can see in the figure below, we have dissected the Tutorialstrend homepage's user interface into its component parts.
Logo at the top can be seen as an individual component, the select category can be seen as an individual component, the sidebar links is an individual component, we can merge all of these individual components to make a parent component which will be the final UI for the homepage.
We can see how this strategy will result in the following advantages.
Types of Component
As we all know, React uses the JSX syntax to allow us to combine HTML and JavaScript. These React components may be defined and used in anywhere in your ReactJS project.
There are primarily two types of components in ReactJS. Those are:
1. Functional Components
They are simply JavaScript functions that may or may not receive data as arguments or parameters. By creating a javascript function, we can construct a functional component in React. The functional components are the functions that takes Props and return JSX. The functional components don’t have the lifecycle methods and state, but they may be provided by simply implementing React Hooks. Debugging, reading, and testing functional components are always easy.
import './App.css';
// Functional Component Example
const functiontest = () => {
return (
<div>
<p>Function Test</p>
</div>
)
}
export default functiontest;
In the code above, it is a very simple component that consists of a constant variable functiontest that is assigned to an arrow function which returns JSX.
Output
2. Class Components
The class component has the capability of performing every function of the functional component and at the same time some additional capabilities as well. It can efficiently make use of the main functions of React, props, state and lifecycle methods as well. We must first import the "React.Component" or extract the Component like "Component" from React before we construct our class-based component.
import './App.css';
import React, {Components} from 'react';
class MyComponent extends Components {
render() {
return (
<div>Class Component Test</div>
);
}
}
export default MyComponent;
Class component syntax differs from functional component syntax. Class components use extends React.Component after declaring the class HelloWorld and requires a render() method to return JSX code.