AnApprentice AnApprentice -4 years ago 69
React JSX Question

redux-form is refreshing the page onSubmit

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? Thanks!

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;

Answer Source

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)} />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download