Blog>
Snippets

Class Component Basic Structure

Demonstrate the basic structure and syntax of a React class component, including the constructor, render method, and state initialization.
import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    // Initialize state
    this.state = {
      myStateValue: 'initial value',
    };
  }

  // Render method to display the component
  render() {
    return (
      <div>
        <h1>{this.state.myStateValue}</h1>
        {/* Other JSX elements */}
      </div>
    );
  }
}

export default MyComponent;
This code snippet defines a basic React class component named 'MyComponent'. It imports React and the Component class, and then extends that class. Within the constructor, it calls super with props to initialize the parent class, and then sets the initial state of the component. The render method returns JSX to be displayed in the UI, which includes a div with an h1 tag displaying a value from the component's state.