Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger a form submit in child component with Redux?

I have a Form component like this:

var React = require('react'),
  ReactRedux = require('react-redux');


var Form = React.createClass({
  render: function(){
    return (
      <form onsubmit={this.onsubmit} action={this.props.action}>
      {this.props.children}
      </form>
    );
  },
  // Method for parent component to call
  submit: function() {
    // do submission and return Promise so caller can take actions
  },
  onsubmit: function(e) {
    // validation, make requests, etc
  }
});

function mapStateToProps(state) {
  return state;
}

module.exports = ReactRedux.connect(mapStateToProps)(Form);

Inside my render of a component I have <Form id="paymentform" ref="form" action="/self">.

I can't do this.refs.form.submit(); because this.refs.form points to the Connector. As I understand it, Connectors are the funnels for reducers to update props, however doing that can't trigger a call to submit.

The use case is basically to have the form submit from another action, which will kick off what the Form component is supposed to do such as validation and XHR requests.

I can do React.findDOMNode(this.refs.form).submit() but that doesn't answer the actual question of hitting a component method from outside.

What am I doing wrong here?

like image 921
Dave Stein Avatar asked Jan 18 '26 03:01

Dave Stein


1 Answers

You can get the wrapped component instance, if necessary, with getWrappedInstance:

this.refs.form.getWrappedInstance().submit()
like image 120
Michelle Tilley Avatar answered Jan 19 '26 19:01

Michelle Tilley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!