Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I declare additional property for React class component?

I rewrite my React Project with TypeScript. now I know how to declare property interface and state interface for a Class Component, simple like this:

export interface ComponentProps {
    propName: string
}

interface ComponentState {
    stateName: number
}

class myComponent extends React.Component<ComponentProps, ComponentState> {
...
}

but error accur when I do something in componentDidMount() lifecycle:

componentDidMount() {
    this.customProperty = 26;  // here I could save an id returned by setInterval to cancel it in the componentWillUnmount() for example.
}

[ts] Property 'customProperty' does not exist on type 'MyComponent'. [2339] What can I do to declare additional property correctly, not just simple silence the error.

I've learned the basic of typescript.

import React, { Component } from 'react';

export interface CheckoutProps {
    total: number;
    customer: string;
}

interface State {
    isChecking: boolean;
}

class Checkout extends Component<CheckoutProps, State> {
    state = {
        isChecking: false
    };

    componentDidMount() {
    this.customProperty = 'sean';
    }

    render() {
        return <div>hello</div>;
    }
}

export default Checkout;
like image 703
seanbruceful Avatar asked Jan 11 '19 13:01

seanbruceful


1 Answers

Class level properties can be defined after the class declartion,

They can be initialized either at the time of declartion or in constructor.

Change your Class To :-

class Checkout extends Component<CheckoutProps, State> {
    customProperty:string=''; //Here,you can define your class level properties

    state = {
        isChecking: false
    };

    componentDidMount() {
    this.customProperty = 'sean';
    }

    render() {
        return <div>hello</div>;
    }
}

Hope this helps,

Cheers !!

like image 91
Sahil Arora Avatar answered Oct 02 '22 16:10

Sahil Arora