react class component in react typescript code example
Example 1: typescript react class component
import * as React from 'react';
export interface TestProps {
count: number;
}
export interface TestState {
count: number;
}
class Test extends React.Component<TestProps, TestState> {
state = { count:0 }
render() {
return ( <h2>this is test</h2> );
}
}
export default Test;
Example 2: how to use class component in typescript react
import React, { Component } from 'react';
type Props = { head ?: string , age ?: number };
type State = { num: number };
type DefaultProps = { head : string, age : string }
class Counter extends Component <Props, State, DefaultProps> {
static defaultProps : DefaultProps = {
head: "Heading is Missing",
age: "Age is missing",
};
state: State = {
num: 0,
};
render() {
const add = () => this.setState({ num: this.state.num + 1 }) ;
return (
<div>
<h1> { this.props.head } </h1>
<p> Age: { this.props.age } </p> <br />
<h3> { this.state.num } </h3>
<button onClick={add}>Add 1</button>
</div>
);
}
}
export default Counter;