I have a simple set of radio buttons inside a redux-form. I need the onChange event of the radio button group to trigger the onSubmit
event of the form.
I'm using redux-form v5.3.1
Setup
RadioFormContainer.js
class RadioFormContainer extends Component {
render() {
const {submit} = this.props;
return (
<RadioForm submit={submit} />
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
submit: function(values, dispatch) {
// API call after validation
}
}
};
RadioForm.js
class RadioForm extends Component {
render() {
const {
submit, // custom post-validation handler
// via redux form decorator:
handleSubmit,
submitting
} = this.props;
return (
<form onSubmit={handleSubmit(submit)}>
<input {...radioField}
checked={radioField.value == "one"}
type="radio"
value="one"
disabled={submitting} />
<input {...radioField}
checked={radioField.value == "two"}
type="radio"
value="two"
disabled={submitting} />
</form>
);
}
}
Attempted implementations, not working
1. Call handleSubmit
from componentWillReceiveProps
on the RadioForm
kyleboyle's proposal here simply doesn't work. When I call nextProps.handleSubmit
from componentWillReceiveProps
, I get this familiar error, Uncaught Error: You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop
componentWillReceiveProps(nextProps) {
if (nextProps.dirty && nextProps.valid) {
let doubleDirty = false;
Object.keys(nextProps.fields).forEach(key => {
if (nextProps.fields[key].value !== this.props.fields[key].value) {
doubleDirty = true;
}
});
if (doubleDirty) {
nextProps.handleSubmit();
}
}
}
2. Call submit
on RadioForm
from the onChange
handler
erikras proposes this here. But it doesn't work for me because it would skip validation.
<input // ...
onChange={(event) => {
radioField.handleChange(event); // update redux state
this.submit({ myField: event.target.value });
}} />
I think Bitaru (same thread) is trying to say the same thing in his reply, but I'm not sure. Calling onSubmit
for me causes the exception Uncaught TypeError: _this2.props.onSubmit is not a function
3. Call submit
on the form via this.refs
This causes the form to actually submit, totally skipping redux-form
Per: How to trigger a form submit in child component with Redux?
<input // ...
onChange={(event) => {
radioField.onChange(event);
this.refs.radioForm.submit();
}} />