React Components
React components are the core building blocks of a React application that represent how a particular element would be visualized on the User Interface. There are two types of Components in React.
-
Functional Components
-
Class Based Components
Functional components are what Modern React Applications use. React suggests we use functional components after React 16.8. Class-based components, however, is the legacy way of declaring components which help us track the lifecycle of the components more accurately.
Let’s see examples of how Functional and Class Based Components are declared in React.
Functional Components
Functional Components are nothing but normal JavaScript functions that return a piece of JSX code or a React Element.
const App = () => {
return (
<div className="app">
<h1>App Component</h1>
</div>
);
};
As you can see, our functional component is a normal JS function that returns a piece of JSX. That’s it.
Class-Based Components
Class-based components is a JavaScript Class that has a render method which returns a piece of JSX or React Element.
class About extends React.Component {
render() {
return (
<div className="app">
<h1>App Component</h1>
</div>
);
}
}
So once again, class-based components have a render method that returns a piece of JSX instead of returning the JSX directly like in Functional Components.
The difference between class-based and functional components is how they return JSX or React Element. Class-based components have a render method that returns a piece of JSX whereas Functional Components return the piece of JSX.
Declaring state and using props is also different in both Components but we will discuss more about that later.
Rendering a Component on the screen
To render a component on the screen, we use the render() method provided to us by ReactDOM. We directly add our component inside the render method and since we have to use JSX to render a component, we represent the component as <App />.
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
const rootElement = document.getElementById("root")!;
const root = ReactDOM.createRoot(rootElement);
root.render(<App />);
Component Composition
A jargon used in the industry
It refers to using two or more components with each other. Our App Component uses Component Composition when it consists of other components within it.
export default function App() {
return (
<div className="App">
<User name="John Doe" email="xyz@xyz.xyz" />
</div>
);
}
In the above example, the App component has a User component. And when two or more components are used to create a component, it is known as component composition.
Click Here