Created
January 29, 2019 16:16
-
-
Save furkancelik/400b988386423b99273e0ffb514cf692 to your computer and use it in GitHub Desktop.
React Hooks Form Example
This file contains hidden or 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 React, { useState } from "react"; | |
function useInput(initialValue) { | |
const [value, setValue] = useState(initialValue); | |
function handleChange(e) { | |
setValue(e.target.value); | |
} | |
return { | |
value, | |
onChange: handleChange | |
}; | |
} | |
function formExample() { | |
const input1 = useInput(""); | |
const input2 = useInput(""); | |
return ( | |
<form | |
onSubmit={e => { | |
e.preventDefault(); | |
console.log(input1.value, input2.value); | |
}} | |
> | |
<input {...input1} /> | |
<br /> | |
<input {...input2} /> | |
<br /> | |
<button type={"submit"}>Gönder</button> | |
</form> | |
); | |
} | |
export default formExample; |
This file contains hidden or 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 React, { useState } from "react"; | |
function formExample() { | |
const [form, setInput] = useState({ | |
input1: "", | |
input2: "" | |
}); | |
const handleChange = name => e => { | |
const newForm = { | |
...form, | |
[name]: e.target.value | |
}; | |
setInput(newForm); | |
}; | |
return ( | |
<form | |
onSubmit={e => { | |
e.preventDefault(); | |
console.log(form); | |
}} | |
> | |
<input | |
type={"text"} | |
name={"input1"} | |
value={form.input1} | |
onChange={handleChange("input1")} | |
/> | |
<br /> | |
<input | |
type={"text"} | |
name={"input2"} | |
value={form.input2} | |
onChange={handleChange("input2")} | |
/> | |
<br /> | |
<button type={"submit"}>Gönder</button> | |
</form> | |
); | |
} | |
export default formExample; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment