In this lesson, we are going to discuss how to use states and event handlers to collect user input via forms.
So far, we've used onClick
as a simple example to demonstrate event handling. However, handling forms requires more than just onClick
. To manage form interactions, we need to understand two key events: onChange
and onSubmit
.
Use onChange to access user input
The onChange
event will be fired when the user types inside a input field, the associated event object will pass the user input to the event handler function, which can be accessed like this:
1export default function App() {
2 return (
3 <input
4 type="text"
5 onChange={(e) => {
6 console.log(e.target.value);
7 }}
8 />
9 );
10}
e.target.value
returns the current user input, and the above example will output whatever the user types to the console.
In practice, we often use states to capture and store user inputs. For example, instead of logging to the console, setText(e.target.value)
will use the user input to update the state text
.
1import { useState } from "react";
2
3export default function App() {
4 const [text, setText] = useState("");
5 return (
6 <>
7 <p>Input: {text}</p>
8 <input type="text" onChange={(e) => setText(e.target.value)} />
9 </>
10 );
11}
This technique applies to most other input fields, such as password
, email
, number
, radio
, date
, time
, range
, and color
. For all of these input fields, the user input can be accessed via e.target.value
.