Created
November 21, 2022 12:21
-
-
Save adeleke5140/9a035395096c1358ae23bebe30557c16 to your computer and use it in GitHub Desktop.
creating initial formData and updating formData
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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