DEV Community

Cover image for Class Component with React Typescript
samira saad
samira saad

Posted on

Class Component with React Typescript

What is a Component?

A component is an independent, reusable code block which divides the UI into smaller pieces.

What are Class Components?

Class components are ES6 classes that return JSX


Using TypeScript together with React has proven to be a powerful combination.

The “older way” of doing components is with class components. And they can keep state per class. State is like props, but private and only controlled by the component itself.

How to create class component using TypeScript

Class components need to be extended from the base React.Component class.

import React, { Component } from 'react';

import React, { Component } from 'react';

type CounterProps = {
  header: string;
};

type CounterState = {
  value: number;
};

class Counter extends React.Component<CounterProps, CounterState> {

  state: CounterState = {
    value: 0,
  };

  render() {
    const { header } = this.props;
    const { value } = this.state;

    return (
      <div>
        <h1>{header}</h1>
        <p>{value}</p>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

1- The CounterProps type is used to declare what type the properties of this component support.

2- This is similar to declaring types with prop-types but without any additional packages and the result of type checking is available at design time. You won't need to run the project to figure out that some types are not correctly passed.

3- Class properties are useful for storing some data that should not affect re-render of a component.

In
the example below, it is a helloMessage that changes when a component is mounted. Its update won't trigger re-rendering.

import React, {Component} from "react";

type CounterProps = {
  value: number;
};

class Counter extends Component<CounterProps> {

   // It won't be possible to assign a value 
  // with a different type to this property.

  helloMessage: string;

  componentDidMount() {
    helloMessage = "Hi! I'm mounted.";
  }

  render() {
    return <p>{this.props.value}</p>;
  }
}
Enter fullscreen mode Exit fullscreen mode

pass a React component down as a prop to a child component

Within TypeScript, React.Component is a generic type (React.Component), so you want to provide it with (optional) prop and state type parameters:

class Test extends Component<PropsType,StateType> {
  constructor(props : PropsType){
        super(props)
  }

  render(){
    console.log(this.props) 
    return (
        <p>this.props.whatever</p> 
    )
  }

};
Enter fullscreen mode Exit fullscreen mode

*And here how to get props of component
*

type ViewProps = React.ComponentProps<typeof View>
// or
type InputProps = React.ComponentProps<'input'>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)