Home > Software engineering >  How to use href with onClick() in IonButton?
How to use href with onClick() in IonButton?

Time:09-22

The below onClick() function works as intended without href. But when I add in the href, only the href seems to run, not the onClick() function. How do I both run the onClick() function and also send the user to a new page?

                <IonButton
                    color="primary"
                    onClick={() => {saveData()}}
                    href="/create/"
                >Save</IonButton>

CodePudding user response:

you do not really want to use href use history

const history = useHistory();
<IonButton color="primary"
  onClick={(event) => { 
      event.preventDefault();
      saveData(); 
      history.push("/create")}}
> Save
</IonButton>

CodePudding user response:

preventDefault() method of a JS event will restrict the JS engine to execute the default functionality of the HTML tag to be performed on any event. Which in your case is, navigating to the URL mentioned in href attribute of <a> tag.

Call preventDefault of the click event in the handler like following:

const history = useHistory();

// ....

const saveData = event => {
  event.preventDefault();

  // here you can implement your logic
  history.push("/create");
}
  • Related