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?
To get input values on form submit in React:Store the values of the input fields in state variables. Set the onSubmit prop on the form element. Access the values of the input fields in your handleSubmit function.
A <form> with a <button> or <input> with type=submit will get submitted when the user presses Enter in any of the form's <input type=text> . If you rely on an onClick of a button, the user must click the button or focus it and press Enter/Spacebar. Using onSubmit will enable both use cases.
Grabbing data from a FormData object If you want to snitch into a FormData object visit the example HTML form in a browser and place a breakpoint on console. log(event. formData) . Fill and submit the form with the browser's console opened and save the object as a global variable.
In HTML, form data is usually handled by the DOM. In React, form data is usually handled by the components. When the data is handled by the components, all the data is stored in the component state. You can control changes by adding event handlers in the onChange attribute.
There are a few ways to do this:
1) Get values from array of form elements by index
handleSubmit = (event) => { event.preventDefault(); console.log(event.target[0].value) }
2) Using name attribute in html
handleSubmit = (event) => { event.preventDefault(); console.log(event.target.elements.username.value) // from elements property console.log(event.target.username.value) // or directly } <input type="text" name="username"/>
3) Using refs
handleSubmit = (event) => { console.log(this.inputNode.value) } <input type="text" name="username" ref={node => (this.inputNode = node)}/>
Full example
class NameForm extends React.Component { handleSubmit = (event) => { event.preventDefault() console.log(event.target[0].value) console.log(event.target.elements.username.value) console.log(event.target.username.value) console.log(this.inputNode.value) } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" name="username" ref={node => (this.inputNode = node)} /> </label> <button type="submit">Submit</button> </form> ) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With