Developer Docs

React Class Component

Components can be defined as ES6 classes and are a common way of defining components in React. The state object type must be defined and passed in as the second generic parameter to the class component. It is then initialised in the constructor, setting name to the empty string.

import React, { Component } from "react";

interface IPerson {
    name: string;
}

export default class PersonInfo extends Component<{}, IPerson> {
    constructor(props: any) {
        super(props);
        this.state = { name: "" };
    }

    render() {
        return (
            <>
                <div>
                    <p>Entered Name: {this.state.name}</p>
                    <p>Name</p>
                    <input
                        type="text"
                        onChange={(e) => {
                            this.setState({ name: e.target.value });
                        }}
                    />
                </div>
            </>
        );
    }
}

To change state you must call the setState function with the updated value, in this case we are taking the value of the text field and setting the name state to this value. For more information on managing state and lifecycle methods, you can checkout the official documentation.

On this page