1

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>
esafresa
  • 480
  • 7
  • 19

2 Answers2

3

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>
Aaron Saunders
  • 33,180
  • 5
  • 60
  • 80
2

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");
}
QueEffCh
  • 25
  • 6
Haider Ali Anjum
  • 831
  • 1
  • 9
  • 20
  • So i'm more asking what the best way to "not" prevent default is while also using onClick. right now i just put window.location.href in the onClick function but, well, maybe that's fine? it doesn't seem like it fits into the react or ionic framework well though – esafresa Sep 18 '21 at 19:51
  • As ReactJS is a SPA styled library. it uses only static routing. if you do window.location.href, it will reload the complete page. which will be a re-render of App.js. So, using a library like react-router-dom, you can redirect to another React Route, Also, it will be using the Link component instead of the tag. – Haider Ali Anjum Sep 18 '21 at 20:37
  • Ah that makes a lot of sense, ty! – esafresa Sep 20 '21 at 16:14