Skip to content

Instantly share code, notes, and snippets.

@adeleke5140
Created November 21, 2022 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adeleke5140/9a035395096c1358ae23bebe30557c16 to your computer and use it in GitHub Desktop.
Save adeleke5140/9a035395096c1358ae23bebe30557c16 to your computer and use it in GitHub Desktop.
creating initial formData and updating formData
import { useState } from "react"
const defaultFormData = {
title: "",
body: ""
}
export default function Form() {
const [formData, setFormData] = useState(defaultFormData)
const { title, body } = formData
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFormData({
...formData,
[e.target.id]: e.target.value
})
}
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
console.log(formData)
setFormData(defaultFormData)
}
return (
<div>
<h1>Form</h1>
<p>Create a post</p>
<form onSubmit={onSubmit}>
<label htmlFor="title">Title</label>
<br />
<input type="text" id="title" value={title} onChange={onChange} />
<br />
<br />
<label htmlFor="body">Body</label>
<br />
<input type="text" id="body" value={body} onChange={onChange} />
<br />
<br />
<button type="submit">Upload post</button>
</form>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment