-1

I want my button to:

  1. first trigger a POST request with its onClick callback
  2. then navigate to another page using react-router facilities

I have proposals for each case.

This is how I can achieve the callback handling:

<button onClick={handleSubmitfunc}>Submit</button>

This is how I see the navigation:

<Link to='/secondpage' state={{from: variable}}>Submit</Link>

My code below tries to resume the two requierements, but doesn't achieve the goal. Only the callback is triggered but not the navigation:

<Link 
 to="/secondpage"
 onClick={handleSubmitfunc}
 state={{from: email}}>
Clickable Link
</Link>

Does the combination fail because I have a state prop?

For reference, I've seen the issue before in: How to use onClick event on react Link component?. That didn't help much.

exaucae
  • 2,071
  • 1
  • 14
  • 24
orgee
  • 65
  • 1
  • 8
  • you can create an onsubmit handler that gets activated onclick, does whatever you want. then you can push the url once you are done with the function. It depends on what version of react router you use, it can be history.push("yourUrl") – wowza_MAN Feb 05 '22 at 19:53
  • Please include all relevant code in your question. What is this `handleSubmitfunc` function doing when clicked? Where is this link locating in code? I suspect you are rendering a form and likely preventing *some* default behavior and breaking the link behavior. – Drew Reese Feb 05 '22 at 23:09

1 Answers1

2

You can use useNavigate hook for redirection.

import { useNavigate } from 'react-router-dom';
...

const navigate = useNavigate()
...

...

const handleSubmitfunc = async () => {
  await /* API call here */


  navigate('<route here>');
}

Umair Riaz
  • 456
  • 3
  • 12
  • Thanks for your answers guys, I managed to get it working looking at this: https://stackoverflow.com/questions/64566405/react-router-dom-v6-usenavigate-passing-value-to-another-component/64566486 – orgee Feb 06 '22 at 12:07