I have a redux form that when submitted, is causing the entire browser page to refresh which is not desired...
What am I doing wrong here to cause the page to refresh on submit?
Rate.js
import React from 'react';
import RateForm from '../../components/rate/RateForm';
class Rate extends React.Component {
handleSubmit(data) {
alert('x')
console.log('handleSubmit');
console.log(data);
}
render() {
const fields = [
{
name: 'execution',
type: 'select',
options: [
{ label: '5', value: '5' },
],
},
]
return (
<div>
<RateForm fields={fields} handleSubmit={this.handleSubmit.bind(this)} />
</div>
)
}
}
export default Rate;
RateForm.js
import React from 'react';
import { Field, reduxForm } from 'redux-form';
const renderField = ({ input, field }) => {
const { type, placeholder } = field
if (type === 'text' || type === 'email' || type === 'number' || type === 'checkbox') {
return <input {...input} placeholder={placeholder} type={type} />
} else if (type === 'select') {
const { options } = field
return (
<div>
<label>{field.name}</label>
<select name={field.name} onChange={input.onChange}>
{options.map((option, index) => {
return <option key={index} value={option.value}>{option.label}</option>
})}
</select>
</div>
)
} else {
return <div>Type not supported.</div>
}
}
class RateForm extends React.Component {
render() {
return (
<form onSubmit={this.props.handleSubmit}>
{this.props.fields.map(field => (
<div key={field.name}>
<Field
name={field.name}
component={renderField}
field={field}
/>
</div>
))}
<button type="submit">Submit</button>
</form>
)
}
}
RateForm = reduxForm({
form: 'rateForm'
})(RateForm);
export default RateForm;
Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.
To prevent form submission when the Enter key is pressed in React, use the preventDefault() method on the event object, e.g. event. preventDefault() . The preventDefault method prevents the browser from refreshing the page when the form is submitted.
You need to pass the handleSubmit
function as handler to the RateForm
component by the reference name onSubmit
.
Use this
<RateForm fields={fields} onSubmit={this.handleSubmit.bind(this)} />
inside render
method:
render(){
const { handleSubmit, ... } = this.props;
return(
<form onSubmit={handleSubmit(this.yourSubmitFunction)}></form>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With