Socrates
Socrates

Reputation: 9574

Get React state field list

Is there a way to get a list of state field in a React component?

I need a list of fields inside a React.Component state, because I need to check the existence of a field at runtime. The following code example has a method getStateFieldList() that aims at working with a list of state fields.

export class MaskCompanyDetail extends React.Component<MaskCompanyDetailProps, MaskCompanyDetailState> {
    public constructor(props: any) {
        super(props);

        // Set field defaults.
        this.state = {
            fieldId: 0,
            fieldCompanyName: '',
            fieldStreetName: '',
            fieldStreetNumber: '',
            fieldZip: '',
            fieldCity: '',
            fieldCountry: '',
            fieldComment: '',
        };
    }

    private getStateFieldList(): string[] {
        // I would like to do something like:
        for (const stateField of this.state) {
            // Do something with stateField.
            ...
        }
    }
}

Upvotes: 0

Views: 385

Answers (1)

Gowri Pranith Kumar
Gowri Pranith Kumar

Reputation: 1685

Object.keys(this.state) gives the list of keys in the state object which can be used to check the existence of a particular field

Upvotes: 2

Related Questions