Class Based Components

Class Based Components

Table of contents

Introduction

  1. In class-based components first, we need to create a class by using the class keyword and then extend it to react. component using extends.

  2. react.component will be imported from react.

  3. The only compulsory method in this class is render which will return some JSX which will be added to the dom.

  4. Passing props in class- based components

    example:

     // Parent component
     class ParentComponent extends React.Component {
       render() {
         const message = "Hello, world!";
         return (
           <ChildComponent message={message} />
         );
       }Creat
     }
    
     // Child component
     class ChildComponent extends React.Component {
       render() {
         return (
           <div>{this.props.message}</div>//passed in a prop
         );
       }
     }
    
  5. In a React class component, you can create and manage multiple states using the setState method provided by the Component base class.

     class MyComponent extends React.Component {
       constructor(props) {
         super(props);
    
         this.state = {
           name: "John",
           age: 25,
           isStudent: true
         };
       }
    
       render() {
         return (
           <div>
             <p>Name: {this.state.name}</p>
             <p>Age: {this.state.age}</p>
             <p>Student: {this.state.isStudent ? "Yes" : "No"}</p>
           </div>
         );
       }
     }
    
  6. In class-based React components, you can update the component's state by calling the setState() method provided by the Component base class.

     class MyComponent extends React.Component {
       constructor(props) {
         super(props);
    
         this.state = {
           count: 0
         };
    
         this.handleClick = this.handleClick.bind(this);
       }
    
       handleClick() {
         this.setState({ count: this.state.count + 1 });
       }
    
       render() {
         return (
           <div>
             <p>Count: {
    
     this.state.count 
    
     // for multiple states update here only   
                }</p>
             <button onClick={this.handleClick}>Increment</button>
           </div>
         );
       }
     }
    
  7. Do not do this:

     this.state.count=10
     // not preferred