0

I am using BrowserRouter in my React project, but there is a form page where I want to use a Link component to: submit the form and to redirect me to the homepage without reloading the page.

<form onSubmit={handleSubmit}>

   /* blablabla */

   <Link to={`/homepage`} className="button">
       Home
   </Link>

</form>

But since the Link is an "a" component I can't make it "type=submit". So my problem is not about how to redirect to homepage, because it works, my problem is that I want to also submit the form.

How can I use the Link React component to redirect to the homepage without reloading the page AND ALSO to submit the form.

Pettko
  • 39
  • 1
  • 2
  • 7

1 Answers1

1

Try with useHistory in your submit function

import { useHistory } from "react-router-dom";


export default function App() {
  let history = useHistory();

  const handleSubmit = e => {
   e.preventDefault();
   e.stopPropagation();
   ...                                
   history.push("/homepage");
  };

  return (
   <form onSubmit={handleSubmit}>
     ...
     <button type="submit">Create</button>
   </form>
  )
};

Demo : Stackblitz

MB_
  • 1,667
  • 1
  • 6
  • 14
  • Thank you so much, this is what I was looking for! However the whole goal of mine was that I wanted to validate some form fields before letting the user to submit it. This method overrides the "required" thing on the input field, somehow it won't stop the submitting. Anyways, an "if" case solved this problem. Thanks again! – Pettko Apr 11 '21 at 16:05
  • @Pettko yes, you need to use a condition to verify if the input field is empty or not before the redirection. You can check 2 demos here with validation and redirection (first one with react-boostrap, the second with Material-ui and react-hook-form) -> https://stackoverflow.com/questions/66676556/how-to-copy-input-data-from-one-component-to-another-component/66678662?noredirect=1#comment117993536_66678662 – MB_ Apr 11 '21 at 16:18