I am new to React;I am learning about React Form. I understand the code but I do not really understand the concept behind and why we use this line " onChange={(e) => setName(e.target.value)}".
Thank you for your help.
They used this example:
import ReactDOM from 'react-dom';
function MyForm() {
const [name, setName] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
alert(`The name you entered was: ${name}`)
}
return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<input type="submit" />
</form>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
CodePudding user response:
means e is the event that is happening which here is change, target is the element that triggered the event, which here is the input, and value is the value of the input element Onchange is as the name suggests and setState is used to change the state you defined eariler you should read the documentation as well it would clear stuff up maybe an online explanation on youtube anyways all the best for your React journey
CodePudding user response:
You have two different things happening here.
Event (e)
First you have e
which is short for event
. To understand what it does change onChange={(e) => setName(e.target.value)}
to onChange={(e) => console.log(e)}
. Inspect the log and you'll find a list of events in which one of them is target
. Open target (if not already opened) and within target, you'll find value
. In short, this is the target value that's being typed in your input, it's what the user is typing.
useState
Your using state to track the value in your input. So [name] is the getter and [setName] is the setter. If you notice in your alert you have alert(
The name you entered was: ${name})
. The variable name
is the getter which means it holds the current value of the state. On the other hand setName
will set that value. It's able to do so because you're setting and tracking the value here on change onChange={(e) => setName(e.target.value)}
.
CodePudding user response:
There are at least 5 concepts that I can think of being used in this single line that I recommend you to learn about
- Higher-Order Functions
- Anonymous functions
- Arrow Functions
- State
- Synthetic Events
To start your journey, just know that this code onChange={(e) => setName(e.target.value)}
is the same as the one below:
function clickHandler(e) {
setName(e.target.value)
}
<input
type="text"
value={name}
onChange={clickHandler}
/>
Maybe that makes things clearer.