Reputation: 9574
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
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