I am having some difficulty getting my input form to reset on submit. I would like for the input field to reset to a blank value when the form is submitted successfully, but for the time being I am also fine with it just resetting onSubmit in general, neither of which I have been able to figure out so far. Specifically, what I tried was:
class SubscribeForm extends React.Component {
constructor(props, ...args) {
super(props, ...args)
this.state = {
status: null,
msg: null,
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
this.setState({ value: '' });
}
With the form layout:
<form onSubmit={this.handleSubmit} action={action} method="post" id="alert-form" noValidate>
<input
ref={node => (this.input = node)}
type="email"
defaultValue=""
name="EMAIL"
required={true}
placeholder={messages.inputPlaceholder}
/>
<button
disabled={this.state.status === "sending" || this.state.status === "success"}
onClick={this.onSubmit}
type="submit"
className="btn-group"
id="AlertButton"
>
<p>Sign Up</p>
</button>
</form>
However, calling {this.handleSumbit} in the onSubmit prop of the Form does not appear to have any result when the button is actually clicked. Is there anything obvious i'm missing here or is it a more complex problem?
Provided below is the full relevant code snippet:
class SubscribeForm extends React.Component {
constructor(props, ...args) {
super(props, ...args)
this.state = {
status: null,
msg: null,
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
this.setState({ value: '' });
}
onSubmit = e => {
e.preventDefault()
if (!this.input.value || this.input.value.length < 5 || this.input.value.indexOf("@") === -1) {
this.setState({
status: "error"
})
return
}
const url = getAjaxUrl(this.props.action) + `&EMAIL=${encodeURIComponent(this.input.value)}`;
this.setState(
{
status: "sending",
msg: null
}, () => jsonp(url, {
param: "c"
}, (err, data) => {
if (err) {
this.setState({
status: 'error',
msg: err
})
} else if (data.result !== 'success') {
this.setState({
status: 'error',
msg: data.msg,
})
} else {
this.input.defaultValue = "";
this.setState({
status: 'success',
msg: data.msg,
inputPlaceholder: "E-mail"
})
}
})
)
}
render() {
const { action, messages, className, style, styles } = this.props
const { status, msg } = this.state
return (
<div className={className} style={style}>
<form onSubmit={this.handleSubmit} action={action} method="post" id="alert-form" noValidate>
<input
ref={node => (this.input = node)}
type="email"
defaultValue=""
name="EMAIL"
required={true}
placeholder={messages.inputPlaceholder}
/>
<button
disabled={this.state.status === "sending" || this.state.status === "success"}
onClick={this.onSubmit}
type="submit"
className="btn-group"
id="AlertButton"
>
<p>Sign Up</p>
</button>
</form>
</div>
)
}
}