Reputation: 943
I have a input value which I fail to update after clicking on Reset link
class DiscountEditor extends Component {
render() {
<div className="inline field">
<a className="ui reset" onClick={this.props.onReset}>Reset</a>
<input
value={this.props.discount}
onChange={this.props.onDiscountChanged}>
</input>
</div>
}
}
class SalesLine extends Component {
onReset(lineItem) {
this._discount = 0;
this.forceUpdate();
}
render() {
<DiscountEditor
value={this._discount}
onChange={this.props.onDiscountChanged}
onReset={this.onReset.bind(this)}
</DiscountEditor>
}
}
as I click on reset button DiscountEditor component will be rendered again and the this.props.discount has the correct value which is zero but the input value will remain the same and won't get updated to zero. Why though?
Upvotes: 1
Views: 68
Reputation: 6803
Assign _discount to your state in the constructor and from there on update the state
class SalesLine extends Component {
constructor(props) {
super(props);
this.state = {discount: this.props.discount};
}
onReset(lineItem) {
this.setState({discount: 0});
}
render() {
return <DiscountEditor
value={this.state.discount}
onChange={this.props.onDiscountChanged}
onReset={this.onReset.bind(this)}
</DiscountEditor>;
}
}
Upvotes: 1
Reputation: 1309
You called the prop value
but you are using this.props.discount
. If you change it to
<input
value={this.props.value}
onChange={this.props.onDiscountChanged}>
</input>
it should work.
You should also put discount
into state in your SalesLine
component instead of calling forceUpdate
manually.
class SalesLine extends Component {
constructor(props) {
super(props);
this.state = {discount: 0};
}
onReset(lineItem) {
this.setState({discount: 0});
}
render() {
return <DiscountEditor
value={this.state.discount}
onChange={this.props.onDiscountChanged}
onReset={this.onReset.bind(this)}
</DiscountEditor>;
}
}
Upvotes: 3