Skip to content

Instantly share code, notes, and snippets.

@barhoring
Last active April 20, 2020 19:56
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 barhoring/064cc270e0eec0b3c35de0efa3329b11 to your computer and use it in GitHub Desktop.
Save barhoring/064cc270e0eec0b3c35de0efa3329b11 to your computer and use it in GitHub Desktop.
Simple form that handles input changes with useReducer hook. When the form is submitted the state is printed to the console
import React, { useReducer } from "react";
import styles from "./form.module.css";
const INITIAL_STATE = {
name: "",
email: "",
subject: "",
body: "",
};
// To spare the pain of creating 4 different fuctions to handle the input
// we use a reducer function
const reducer = (state, action) => {
switch (action.type) {
case "updateFieldValue":
return { ...state, [action.field]: action.value };
default:
return INITIAL_STATE;
}
};
const Form = () => {
const [state, dispatch] = useReducer(reducer, INITIAL_STATE);
// `updateFieldValue will be set in action.type in case of input change`
const updateFieldValue = (field) => (event) => {
dispatch({ type: "updateFieldValue", field, value: event.target.value });
};
const handleSubmit = (event) => {
event.preventDefault();
console.log(state);
};
return (
<form className={styles.form} onSubmit={handleSubmit}>
<label className={styles.label}>
Name
<input
className={styles.input}
type="text"
name="name"
value={state.name}
onChange={updateFieldValue("name")}
/>
</label>
<label className={styles.label}>
Email
<input
className={styles.input}
type="email"
name="email"
value={state.email}
onChange={updateFieldValue("email")}
/>
</label>
<label className={styles.label}>
Subject
<input
className={styles.input}
type="text"
name="subject"
value={state.subject}
onChange={updateFieldValue("subject")}
/>
</label>
<label className={styles.label}>
Body
<textarea
className={styles.input}
name="body"
value={state.body}
onChange={updateFieldValue("body")}
/>
</label>
<button className={styles.button}>Send</button>
</form>
);
};
export default Form;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment