Controlled Forms in React

import React from 'react';  export default function LoginForm() {      
return (
<form className="login-form">
<input name="username" type="text" />
<input name="password" type="password" />
<input type="submit" value="Submit" />
</form>
)
}
import React, { useState } from 'react';export default function LoginForm() {         const [formData, setFormData] = useState({         
username: '',
password: ''
})
return (
<form className="login-form">
<input name="username" type="text" />
<input name="password" type="password" />
<input type="submit" value="Submit" />
</form>
)
}
import React, { useState } from 'react';export default function LoginForm() {         const [formData, setFormData] = useState({         
username: '',
password: ''
})
return (
<form className="login-form">
<input
name="username"
type="text"
value={formData.username}
/>
<input
name="password"
type="password"
value={formData.password}
/>
<input type="submit" value="Submit" />
</form>
)
}
import React, { useState } from 'react';

export default function LoginForm() {
const [formData, setFormData] = useState({
username: '',
password: ''
})
const handleChange = (event) => {
setFormData({
...formData,
[event.target.name]: event.target.value
})
}
return (
<form className="login-form">
<input
name="username"
type="text"
value={formData.username}
onChange={handleChange}
/>
<input
name="password"
type="password"
value={formData.password}
onChange={handleChange}
/>
<input type="submit" value="Submit" />
</form>
)
}
import React, { useState } from 'react';

export default function LoginForm() {
const [formData, setFormData] = useState({
username: '',
password: ''
})
const handleChange = (event) => {
setFormData({
...formData,
[event.target.name]: event.target.value
})
}
const handleSubmit = (event) => {
event.preventDefault()
console.log("Your move, dear reader.")
}
return (
<form className="login-form" onSubmit={handleSubmit}>
<input
name="username"
type="text"
value={formData.username}
onChange={handleChange}
/>
<input
name="password"
type="password"
value={formData.password}
onChange={handleChange}
/>
<input type="submit" value="Submit" />
</form>
)
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jeff Golden

Jeff Golden

Frontend developer, mountaineer, husband and dog wrangler.