score:4

Accepted answer
import React from "react";
import { Prompt } from "react-router-dom";
import { useFormik } from "formik";

const MyForm = () => {
  const formik = useFormik({
    initialValues: {
      name: "",
      subject: ""
    },
    enableReinitialize: true,
    onSubmit: (values) => {
      alert(JSON.stringify(values, null, 2));
    },
    onChange: (e) => {
      console.log(e);
    }
  });

  return (
    <div>
      <Prompt
        when={!!formik.dirty}
        message={(location) =>
          `Are you sure you want to go to ${location.pathname}`
        }
      />
      <form id="myForm" onSubmit={formik.handleSubmit}>
        <div className="row">
          <div className="form-group">
            <label htmlFor="name">Name</label>
            <input
              id="name"
              type="text"
              onChange={formik.handleChange}
              value={formik.values.name}
              className="form-control"
              placeholder="Enter name"
            />
            {formik.errors.name ? (
              <div className="text-danger">{formik.errors.name}</div>
            ) : null}
          </div>
          <div className="form-group">
            <label htmlFor="subject">Subject</label>
            <input
              id="subject"
              type="text"
              onChange={formik.handleChange}
              value={formik.values.subject}
              className="form-control"
              placeholder="Email subject"
            />
            {formik.errors.subject ? (
              <div className="text-danger">{formik.errors.subject}</div>
            ) : null}
          </div>
          {formik.dirty && <button tye="submit">Save</button>}
        </div>
      </form>
    </div>
  );
};

export default MyForm;

Related Query

More Query from same tag