Home > Software engineering >  Having two buttons in one React form (or something similar)
Having two buttons in one React form (or something similar)

Time:04-03

Using the solution proposed in the first comment this is my code:

  let ref1 = React.createRef();
  let ref2 = React.createRef();

  async function myHandleSubmit(data){
      if(ref1.current.clicked === true){
        console.log("Ref1");
      }else if(ref2.current.clicked === true){
        console.log("Ref2");
      }
  }

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

But I´m getting this error:

enter image description here

CodePudding user response:

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 refs for both buttons

2.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
let ref1=React.createRef();
let ref2=React.createRef();

assign this ref to both buttons like this

 <FormButtonTop ref={ref1} left id="submit1" type="submit" value="A generator" />
 <FormButtonTop ref={ref2} right id="submit2" type="submit" value="B generator" />

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

 funciton handleSubmit(){
  if(ref1.current.clicked===true){
     //form is submited with submit1 click
     //do your code 
   }elseif(ref2.current.clicked===true){
      //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
      }
   
}
  • Related