Home > database >  React: How form submit refreshes page and come back to the original route?
React: How form submit refreshes page and come back to the original route?

Time:01-21

I am displaying tree component in the left and add_category component in the right part of page. tree node click route to different components on the right.

on page load, page is http://localhost.com first node click route to http://localhost.com/add_category second node click route to edit_category

How form submit in add_category refreshes the page and come back to the original route/location http://localhost.com/add_category ?

Please find the sandbox: hhttps://codesandbox.io/s/shy-snow-nfce4i

thanks

CodePudding user response:

for submit handler event you have to use event.preventDefault()

that will stop refresh the page you will notice in your address it shows extra things to use preventDefault and then use

const history = useHistory();
history.push("/home");

CodePudding user response:

If I understand you correctly, you are looking for a way to redirect after a form request.

In that case, you will need to have a function that handles the form submission and performs the redirect when completed.

If you're using react-router-dom you can do something like this:

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

...

const App = () => {
  ...
  const handleSubmit = () => {
    // do what you need to do
    navigate('/add-category')
  }

  return (
    <div>
      ...
      <form onSubmit={handleSubmit}>...</form>
      ...
    </div>
  )
}
...


  • Related