I want to restore the default values on all input fields and total on the click of button 'Restore Default', but it is not working. In the code I have so far, all the elements are wrapped within a grid.
The SO questions I referred to talk about:
- Wrapping all elements in a form or a div and call reset()
- Use e.target.reset() on the event. I tried this with onClick event of button, but says that reset is not a function.
What is the preferred way to implement this functionality? Thanks in advance!
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
code1: this.props.defaults[0],
code2: this.props.defaults[1],
code3: this.props.defaults[2],
total : 0
};
this.handleInput = this.handleInput.bind(this);
this.restoreDefaults = this.restoreDefaults(this);
}
handleInput() {
//some logic
}
updateCode = (e, k) => {
this.setState({
[`code${k}`]: e.target.value
},
() => {
this.updateTotal();
});
}
updateTotal = () => {
this.setState(prevState => ({
total: (+prevState.code1 + +prevState.code2 + +prevState.code3),
}),
() => {
if (this.state.total !== 100) {
this.setState({
isTotalInvalid: true
});
} else {
this.setState({
isTotalInvalid: false
});
}
});
}
restoreDefaults() {
this.setState({
code1: this.props.defaults[0],
code2: this.props.defaults[1],
code3: this.props.defaults[2],
total: 0,
)};
}
render() {
return (
<Spacer>
<Grid>
<Grid.Row>
<Grid.Column tiny={12} medium={10}>
<input type="number" defaultValue={this.state.code1} min="0" max="100" onKeyPress={this.handleInput} onBlur={e => this.updateCode(e, 1)} />
</Grid.Column>
<Grid.Column tiny={12} medium={10}>
<input type="number" defaultValue={this.state.code2} min="0" max="100" onKeyPress={this.handleInput} onBlur={e => this.updateCode(e, 2)} />
</Grid.Column>
<Grid.Column tiny={12} medium={10}>
<input type="number" defaultValue={this.state.code3} min="0" max="100" onKeyPress={this.handleInput} onBlur={e => this.updateCode(e, 3)} />
Total Field:
<span fontSize={14} weight={700}>{this.state.total}</span>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Button text="Restore Default" type="button" onClick=
{this.restoreDefaults} />
</Grid.Row>
</Grid>
</Spacer>
);
}
}
export default Test;
onBlurinstead of just usingonChange?valueattribute on your input as well that should be controlled by your state