Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - on form submit get POST params

I am using React, and would like to retrieve POST params from a form (see below):

<form ref='form' className="form">
    <input type="text" className="signup-input" />
    <input type="text" className="signup-input" />
    <button className="btn btn-primary" onClick={this._onSubmitClick}>Submit</button>
</form>

In the _onSubmitClick callback, I would like to achieve the same results as calling $(".form").serialize() but without using JQuery.

like image 718
i_trope Avatar asked Feb 25 '15 15:02

i_trope


3 Answers

in addition to the answer i think somebody will love this ;)

export default class LoginView extends React.Component {
    handleSubmit(evt) {
        const formData = Array.from(evt.target.elements)
            .filter(el => el.name)
            .reduce((a, b) => ({...a, [b.name]: b.value}), {});
        console.log(formData);
        evt.preventDefault();
        return false;
    }

    render() {
        return (<form onSubmit={this.handleSubmit}>...</form>)
    }
}
like image 151
Fareed Alnamrouti Avatar answered Nov 16 '22 21:11

Fareed Alnamrouti


You can place ref on each input:

<form ref='form' className="form">
    <input type="text" ref="firstName" className="signup-input" />
    <input type="text" ref="lastName" className="signup-input" />
    <button className="btn btn-primary" onClick={this._onSubmitClick}>Submit</button>
</form>

And then to use React.findDOMNode to access them in _onSubmitClick:

_onSubmitClick: function() {
    var firstName = React.findDOMNode(this.refs.firstName).getValue();
    var lastName = React.findDOMNode(this.refs.lastName).getValue();
    // ...
}
like image 28
Denis Itskovich Avatar answered Nov 16 '22 21:11

Denis Itskovich


var elements = this.refs.form.getDOMNode().elements;

gives you an object containing each of the input nodes, which you could then iterate through.

like image 11
Joe Avatar answered Nov 16 '22 20:11

Joe