I have a form that requests for user's details - username and password, how do I get them in react?
Hello my dear reader, my name's Lucas and today we'll be solving the problem above and beyond that.
To start with, I need you to know that the way you create forms in react is very similar to that of vanilla html. Let's create a simple login form.
<form>
<h3>Username:</h3>
<input type="text" />
<h3>Password:</h3>
<input type="password" />
</form>
This is the simple form we'll be using.
Let's start by creating a state for each input, with empty string to start with
const initialData = {username: "", password:""};
const [userData, setUserData] = useState(initialData);
Next, we destructure the state so that we can interact with its data.
const {username, password} = userData;
What we'll be doing next is this. We want to recognize each input by their names, so we will be giving both of them a corresponding name plus we'll also set the values to the state's value(username and password in useState()):
<form>
<h3>Username:</h3>
<input type="text" name="username" value={username} />
<h3>Password:</h3>
<input type="password" name="password" value={password} />
</form>
Up next, we'll create a function that updates setUserData whenever there's a change within it.
const onChangeHandler =(e) => {
setUserData({... userData, [e.target.name]: e.target.value});
}
Or shorter
const onChangeHandler =(e) => {
const {name, value} = e.target;
setUserData({... userData, [name]: value})
console.log(userData):
}
Finally all we've got to do is attach the function to each input.
<form>
<h3>Username:</h3>
<input type="text" name="username" value={username} onChange={onChangeHandler} />
<h3>Password:</h3>
<input type="password" name="password" value={password} onChange={onChangeHandler} />
</form>
I really love to do for checkbox but then I discovered it will be interesting if you tried it out yourself, using this example. Let me know in the comment section if you did it. I'd be glad to know.
To read and understand more about this topic, visit Reacts official website: https://reactjs.org/docs/forms.html
Did you find this post helpful? Why not give it a like and share with others. 😉
Top comments (4)
Would be simpler just to add the handler to the form's
onChange
event - no need to add it to every fieldThanks a lot @jonrandy, didn't know I could do this until now.
so clean 💖
Great work. Carefully explained