React Functional vs Class Components – Beginners Guide.

August 3, 2022

React being one of the famous frontend framework is used for building different kind of user interface. While working with components in JSX we come across two different types of components.

  1. Functional Components
  2. Class Components

In this article we would be looking at how these components are different. So let’s get started

Before going into class or functional components let’s discuss what’s a react component meant to be :

A component is block of code in which further the components exists to bring any design to small pieces. These are reusable code block and can used or imported independently.
A components play a crucial role while building the complex ui design as we tend to avoid putting everything in a single page.

React has two types of components, lets look into those one by one.

A Functional Component is basically a JavaScript function that return a React JavaScript Xml element(known as JSX).

Let’s have an example to understand

import React from "react";

const Welcome = props => (
    <h1>Welcome🙌, {}</h1>

export default Welcome;
Enter fullscreen modeExit fullscreen mode

In Functional Components there is no render method , they are mainly responsible for UI presentational like a card or button. If Component needs react state , its advised to go with Functional Components.

Class Component is a regular ES6 class that extends the component class from the react library. To return HTML you have to use render() method in it.
You pass props down to class components and access them with _this.props _

class ClassComponent extends React.Component {
 render() {
   return <h1>Hello, world</h1>;

Enter fullscreen modeExit fullscreen mode

If we want to pass some props for the components:

<Component name = “Abhishek Kushwaha” />

In case of FUNCTIONAL COMPONENT , we pass the props as an argument of our function using the construction “”.

function FunctionalComponent(props) {
 return <h1>Hello, {}</h1>;
Enter fullscreen modeExit fullscreen mode

With class components, we need to add this. to refer to props.

class ClassComponent extends React.Component {
render() {
 return <h1>Hello, {}</h1>;
Enter fullscreen modeExit fullscreen mode

Hope you found Helpful ! 😀

Source link

Comments 0

Leave a Reply

Your email address will not be published. Required fields are marked *