Tom Yotwongjai
Tom Yotwongjai

Reputation: 67

How to navigate to new page if submission is successful?

I have a form that is submit with some data. I am able to console.log the data and know that form is submitted but I would like to navigate to different page once my form is submitted and submission condition met.

HandleSubmit condition:

 const handleSubmit = (event) => {
event.preventDefault();
if (Object.keys(errors).length === 0) {
 callback();
} else {
etErrorMessage("Please, submit required data");
setSubmitted(false);
 }
  };

<button onClick={handleSubmit}>Save</button>

Upvotes: 1

Views: 1781

Answers (3)

Tom Yotwongjai
Tom Yotwongjai

Reputation: 67

I actually got it, I feel so dumb. since I have a sperate custom hook file for handling my form events, I just have to create formSubmit to handle my navigation and pass into my custom hook.

Upvotes: 0

Amit Maraj
Amit Maraj

Reputation: 374

If you are using react router, you can use the useHistory hook and then call history.push("/some_url") after your submit. Docs can be found here: https://v5.reactrouter.com/web/api/Hooks

Upvotes: 0

octaviandd
octaviandd

Reputation: 179

If you are using react router, you can use "useNavigate" (https://reactrouter.com/docs/en/v6/getting-started/overview)

If you are not using react router, and you want to change the url, you can use this in your callback.

window.location.href = "http://localhost:8000/test"

Upvotes: 2

Related Questions