Reputation: 1
I want to pass the function 'handleTaxInput' to value prop of input field to set the value of input field to whatever this function returns. But, on console.log(this.state.totalTaxInv)
i'm getting undefined. I'm not getting actual state which i should be getting after running this.handleTaxAmount().
handleTaxAmount(){
if(this.state.cgstsgstRate === 0 || this.state.cgstsgstRate === ""){
return Number(this.state.amount) + Number(this.state.amount) * Number(this.state.igstRate / 100)
} else if(this.state.igstRate === 0 || this.state.igstRate === ""){
return Number(this.state.amount) + Number(this.state.amount) * Number(this.state.cgstsgstRate * 2 / 100)
} else {
return 0
}
}
<div>
<label>Total Inv. Amount</label>
<input name="totalInvAmt" placeholder={this.handleTaxAmount()} value={this.handleTaxAmount()}/>
</div>
I have already initialised all states using constructor .
Upvotes: 0
Views: 894
Reputation: 2314
I can't comment, so I'll have to ask this way. Did you initialize the state using this.setState(...)
or did you just assign the state like this.state = {...}
?
It seems like you want the state to change after calling your function, but you don't set the state anywhere in your function with this.setState(...)
.
Also: Why are you using so many Number
constructors?
Edit (Answer):
handleTaxAmount() {
let result = 0;
if (this.state.cgstsgstRate === 0 || this.state.cgstsgstRate === "") {
result = Number(this.state.amount) + Number(this.state.amount) * Number(this.state.igstRate / 100);
} else if (this.state.igstRate === 0 || this.state.igstRate === "") {
result = Number(this.state.amount) + Number(this.state.amount) * Number(this.state.cgstsgstRate * 2 / 100);
}
this.setState({
variableYouWantToChange: result
});
}
And if you want the value of your input field to change with the state use:
<div>
<label>Total Inv. Amount</label>
<input name="totalInvAmt" placeholder={this.state.variableChangedByFunction} value={this.state.variableChangedByFunction}/>
</div>
If you want to bind every change of the input to run the function do:
<div>
<label>Total Inv. Amount</label>
<input name="totalInvAmt" placeholder={this.state.variableChangedByFunction} value={this.state.variableChangedByFunction} change={this.handleTaxAmount}/>
</div>
and run this.handleTaxAmount = this.handleTaxAmount.bind(this)
in your constructor.
If you want more information about how to use a components state see the docs
Upvotes: 1