I have a simple form in my render
function, like so:
render : function() {
return (
<form>
<input type="text" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="button" onClick={this.handleLogin}>Login</button>
</form>
);
},
handleLogin: function() {
//How to access email and password here ?
}
What should I write in my handleLogin: function() { ... }
to access Email
and Password
fields ?
Use the
change
events on the inputs to update the component's state and access it inhandleLogin
:Working fiddle: http://jsfiddle.net/kTu3a/
Also, read the docs, there is a whole section dedicated to form handling: http://facebook.github.io/react/docs/forms.html
Previously you could also use React's two-way databinding helper mixin to achieve the same thing, but now it's deprecated in favor of setting the value and change handler (as above):
Documentation is here: http://facebook.github.io/react/docs/two-way-binding-helpers.html
I would suggest the following approach:
To improve the user experience; when the user clicks on the submit button, you can try to get the form to first show a sending message. Once we've received a response from the server, it can update the message accordingly. We achieve this in React by chaining statuses. See codepen or snippets below:
The following method makes the first state change:
As soon as React shows the above Sending message on screen, it will call the method that will send the form data to the server: this.sendFormData(). For simplicity I've added a setTimeout to mimic this.
In React, the method this.setState() renders a component with new properties. So you can also add some logic in render() method of the form component that will behave differently depending on the type of response we get from the server. For instance:
codepen
In many events in javascript, we have
event
which give an object including what event happened and what are the values, etc...That's what we use with forms in ReactJs as well...
So in your code you set the state to the new value... something like this:
Also this is the form example in React v.16, just as reference for the form you creating in the future:
If all your inputs / textarea have a name, then you can filter all from event.target:
Totally uncontrolled form
There are a few ways to do this:
1) Get values from array of form elements by index
2) Using name attribute in html
3) Using refs
Full example