Introduction to Class-Based Components in React
In this Blog we will cover what is ClASS BASED components and how to pass PROP in class based component
Class-based components are a foundational concept in React. Although the trend has shifted towards functional components with hooks, understanding class-based components is essential for working with existing codebases and grasping React's core concepts.
Syntax of Class-Based Components
Class-based components in React are defined using ES6 classes that extend the React.Component class. Here’s a basic example:
import React, { Component } from 'react';
class UserClass extends Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
export default UserClass;
-
Extends: The
extends Componentsyntax informs React thatUserClassis a class-based component. -
Render Method: The
rendermethod returns the JSX that will be displayed on the screen.
class userClass extends React.Component{
}
To summarize, we create a JavaScript class UserClass which extends from React.Component that comes from the React library.
How to pass props inside CLASS based Component
Props are used to pass data from parent components to child components. Here's how to work with props in class-based components.
Sending Props:
<UserClass name="John Doe" />
Receiving Props:
We will create a constructor and this constructor will recieve the PROPand will use SUPER keryword to recieve and we always have to write it otherwise it will throw error.
class UserClass extends Component {
constructor(props) {
super(props);
console.log(this.props.name);
}
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
- Constructor: Initializes the component and receives props.
-
Super: Passes the props to the base
Componentclass. - this.props: Accesses the props within the component.
The console will show the value of the prop.
Function Components Comparison
For comparison, here’s how the same task is done using functional components:
const UserFunction = (props) => {
return <h1>Hello, {props.name}</h1>;
}
To use the prop within a class-based component, you would write this.props.name.
The method of sending props is the same for both class-based and functional components. The primary difference lies in how props are received and used: class-based components use the constructor and the super keyword.
Top comments (0)