Reputation: 98
I have a Long form in TypeScript React App, Where we need to hide/show or enable/disable based on value of status.
export interface IState {
Status: string;
DisableBasicForm: boolean;
DisableFeedbackCtrl: boolean;
DisableTypeofReqCtrl: boolean;
DisablePurposeCtrl: boolean;
DisableDutyStation: boolean;
DisableContractManager: boolean;
DisableSection: boolean;
DisableStartDate: boolean;
DisableEndDate: boolean;
DisableEstimateDate: boolean;
DisableTotalBudget: boolean;
DisableDeliveryDate: boolean;
DisableWBS: boolean;
DisableGrant: boolean;
DisableGrantExpiry: boolean;
DisableCaseSubmitter: boolean;
DisablePreparedBy: boolean;
DisablePreparedDate: boolean;
ShowSupplyManagerPanel: boolean;
ShowBudgetOwnerPanel: boolean;
DisableSupplyManagerPanel: boolean;
DisableBudgetOwnerPanel: boolean;
}
while in class I need to initiate the State in constructor, what would be best way to do, I don't need to initiate very variable present in IState?
public constructor(props: IGoodsProps) {
super(props);
//What should be written here, minimal code required.
}
Upvotes: 0
Views: 3658
Reputation: 2437
If you're okay with some of the properties having a default value of undefined
, you can mark them as optional in IState
using ?
. For example (I'm picking some properties randomly since I don't know your requirements):
export interface IState {
Status: string; // this one is required
DisableBasicForm?: boolean; // this one is optional
DisableFeedbackCtrl?: boolean;
// ...
}
Then you can omit the optional properties when initializing the state in the constructor.
Which properties to make optional? If you want any of your booleans to be false by default, in many cases undefined
will work instead because undefined
is "falsey" in JavaScript. (can go into more detail if this doesn't make sense)
Upvotes: 1
Reputation: 73918
If you state implement IState, you would need to initiate each property of IState (based on your logic) because properties in IState are not marked as optional.
Pseudo code example:
public constructor(props: IGoodsProps) {
const {status} = this.props
super(props);
this.state ={
Status: status,
DisableBasicForm: status.Status === 'yourValue',
... // initialize here
}
}
If you have some default value for your state passed as prop you could use object decostructor:
public constructor(props: IGoodsProps) {
const {status} = this.props
super(props);
this.state ={
...status,
DisableBasicForm: status.Status === 'yourValue', // just overwrite this property with your logic
}
}
You can also initialize your state outside the costructor:
class Component extends React.Component<Props, State> {
state: State = {
Status: 'value',
... // initialize here
}
constructor(props: Props) {
...
}
If you have some shared logic for setting your state, and do not want repeat yourself you could evaluate using React.useState
but you component need to be a function.
Upvotes: 1