Joncarre
Joncarre

Reputation: 137

Having two buttons in one React form (or something similar)

Solution: how to implement two functions (with two buttons) using the same information from a single form:

  async function myHandleSubmit(data, event){
      if(event.nativeEvent.submitter?.id === "submit1"){
        console.log("Ref1");
      }else if(event.nativeEvent.submitter?.id === "submit2"){
        console.log("Ref2");
      }
  }

  <Form key={1} onSubmit={handleSubmit(myHandleSubmit)}>
       // More code...
       <FormButtonTop left id="submit1" type="submit" value="Button A" />
       <FormButtonTop right id="submit2" type="submit" value="Button B" />
       // More code...
  </Form>

Upvotes: 0

Views: 1829

Answers (1)

Jatin Parmar
Jatin Parmar

Reputation: 2910

so you have single handler for form submit and you want to perform different action based on which submit button is clicked?right .

you can do this by following steps

1.create state for button clieked

2.onclick of button set which button is clicked

3.at the time of submission check which button is clicked inside submit handlers

for example consider the following code

//infunctional component you can use useRef hook
 const [clickedButton,setClicked] = useState("");

assign click handler to both buttons like this and set clicked button value on click

 <FormButtonTop onClick={()=>{setClicked("firstButton")}} left id="submit1" type="submit" value="A generator" />
 <FormButtonTop  onClick={()=>{setClicked("secondButton")}} right id="submit2" type="submit" value="B generator" />

finally inside your submit handler use clickedButton to check which button is clicked and make a call to appropriate function as shown below

 funciton handleSubmit(event){
 event.preventDefault();
  if(clickedButton==="firstButton"){
     //form is submited with submit1 click
     //do your code 
   }elseif(clickedButton==="secondButton"){
      //form is submited with submit2 click
         ///do your code here for submit2 click
    }else{
        //form is submited by pressing enter key
         // do your code to handle enter key press
      }
   
}

created an example code here.

since form can also be submited using enter key,you will need to set clickedButton="" when enter key is pressed on any text box

Upvotes: 1

Related Questions