Home > Mobile >  Form submission, react-hook-form and state in React
Form submission, react-hook-form and state in React

Time:06-23

I would like to have a button that displays "Edit" to enter Edit mode and (using the same button) "Save" to submit the form.

My problem is that it already submits the form upon pressing the button while the button text "Edit" is showing.

Link to codesandbox, containing the code below.

import "./styles.css";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Button } from "@material-ui/core";

export default function App() {
  //Setting up state
  const [isEditing, setIsEditing] = useState(false);

  //Handler for entering edit mode.
  const handleEnterEditMode = () => {
    setIsEditing(true);
    console.log("Edit mode entered.");
  };

  //Handler that runs on form submission.
  const handleSave = () => {
    console.log("Form submitted.");
  };

  //Setting up some react-hook-forms variables according to their docs
  const {
    register,
    formState: { errors },
    handleSubmit,
    control,
    reset
  } = useForm();

  //In render:

  return (
    <div className="App">
      <form noValidate onSubmit={handleSubmit(handleSave)}>
        <Button
          {...(isEditing ? { type: "submit" } : {})}
          {...(!isEditing ? { onClick: handleEnterEditMode } : {})}
        >
          {!isEditing ? "Edit" : "Save"}
        </Button>
      </form>
    </div>
  );
}

CodePudding user response:

A button inside of a Form element will always fire a Submit event by default. You can give give the button a type attribute of "button", or add a preventDefault() to the onClick method to override this.

CodePudding user response:

Try this approach:

< Button
type = { isSubmiting ? "submit" : null }
>
{!isEditing ? "Edit" : "Save"
} 
</Button>
and also move your onClick condition inside handleEnterEditMode method

  • Related