EN
React - form submit
3
points
In this article we would like to show you how to submit a form in React.
In below example we access form fields with references by React.useRef()
hook to create usernameRef
and passwordRef
that let us to access HTML input elements.
In handleSubmit
function we:
- block page realoding using
preventDefault()
method, - use the references to get field values and create
data
object that is converted to JSON and displayed in console - we can send that JSON with AJAX to backend too.
handleSubmit
function is attached to onSubmit
event property that is fired when submit action occurs - when Submit
button is clicked.
// ONLINE-RUNNER:browser;
// Note: uncomment import lines in your project.
// import React from 'react';
// import ReactDOM from 'react-dom';
const Form = () => {
const usernameRef = React.useRef();
const passwordRef = React.useRef();
const handleSubmit = e => {
e.preventDefault();
const data = {
username: usernameRef.current.value,
password: passwordRef.current.value
};
const json = JSON.stringify(data, null, 4);
console.clear();
console.log(json);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Username: </label>
<input type="text" ref={usernameRef} />
</div>
<div>
<label>Password: </label>
<input type="password" ref={passwordRef} />
</div>
<button type="submit">Submit</button>
</form>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<Form />, root );