Class Component
Class component is child class of React.Component. Class helps us to manage props, states and multiple functions.
Class component name must be starting with Capital letter and it returns html code similar to function component.
As part of this blog, we are going to cover below important topics:
- Class component
- Constructor
- Properties (props)
Follow below steps to create React Class component.
- Create react project using npx create-react-app practice-app command. practice-app is the custom project name.
2. Create Main.js file to create Main Class component.
3. Use below content in global index.js file to load Main component created in above steps to render above component.
Component loading part is similar for both Function and Class component as shown below.
Class Constructor
constructor() is a function having no return type and gets call at the same time when component gets initialize.
Constructor helps us to initialize properties on component initial load. can have no argument as well as parameterized constructor.
Use super() keyword to call parent class constructor and this must to be the first statement in the constructor.
Below is the highlighted constructor code having super() keyword in first line and initializing text property .
In index.js file, load Main component using <Main/> statement.
OUTPUT
React Props
Props is the another way to working with properties. We can not modify props as they are immutable.
Props can be passed as part arguments. Props can only be passed from parent to child components.
Use {this.props.color} statement to access props passed from index.js file using <Main color=”red”/> statement.
Declare color property (props) as red for Main component using <Main color=”red”/> statement inside index.js file.
OUTPUT
Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.