Skip to content

Instantly share code, notes, and snippets.

@furkancelik
Created January 29, 2019 16:16
Show Gist options
  • Save furkancelik/400b988386423b99273e0ffb514cf692 to your computer and use it in GitHub Desktop.
Save furkancelik/400b988386423b99273e0ffb514cf692 to your computer and use it in GitHub Desktop.
React Hooks Form Example
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;
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