If we want to understand How Class components in react are working?, I guess first we need to understand what class components are?
You guys have mostly worked with functional components only in React, I can say i use functional components only. But this was not possible before React 16.8, before that functional components were considered to be the stateless components.
It was only possible after the introduction of Hooks, now functional components are kind of equivalent to class components.
So, basically before the introduction of React 16.8 and hooks, only class components were being used to make any component in a React application as it was possible to manage and change the state of the application.
Now, that we have cleared what exactly a class component is, let us focus on the part where we are going to see how to use them, if given a choice, because there is no plan of removing them from React. So, I guess you guys should know about them as well.
It is pretty basic as the functional component, the component should start with an upper case character only.
Look at the below code to see how to create a class component:
import React from "react";
class Product extends React.componet{
render(){
return(
<div>
<h1>This is a Product Component.</h1>
</div>
)
}
}
export default Product;
class components basically extends from React.component, creating an inheritance. The component also contains a render() method, which basically return HTML.
The properties of class component should be kept in an object called as state. The state should be initiated in a constructor function which will be present inside the class component itself. Look at the below to see how it is achieved.
import React from "react";
class Product extends React.Component{
constructor(){
super();
this.state = {
name:"Shampoo",
price:200,
show:false
};
}
render(){
return (
<div>
<h1>This is a product component.</h1>
<h3>Name: {this.state.name}</h3>
<h3>Price: {this.state.price}</h3>
</div>
)
}
}
export default Product;
super() is used inside the constructor function so that your component can access all the methods of the parent component as well.
If you want to access the properties of the component you have to use this keyword for it.
Now, to change the state of a component let us consider a button element as well which will update the state of the application, this button is going to update the price of the shampoo by 10 every-time we click on it. This will be made possible by using onClick.