skip to Main Content

the navigation does not work , the react router is working correctly when i type down the URL manually also the Links

 const navigate = useNavigate();

 function handleForm() {
    console.log("Form Submitted");
    navigate("/");
  }

 <Form onSubmit={handleForm}>
...
</Form>

To navigate to another webpage in a function and not using Links

3

Answers


  1. you are missing e.preventDefault(); when your are doing form submission. your final code looks like this –

    import { useNavigate } from 'react-router-dom'; 
    function MyComponent() {
      const navigate = useNavigate(); 
      function handleFormSubmit(event) {
        event.preventDefault(); 
        console.log("Form Submitted"); 
        navigate("/");
      }
    
      return (
         <Form onSubmit={handleForm}>
       ...
       </Form>
      );
    }
    

    above would work as expected, also iam assuming you have checked any other errors/bugs and also your Main app is wrapped in BrowserRouter.
    If this still doesn’t work you can also use useHistory instead of useNavigate(), both works same. Let me know if it worked for you!

    Login or Signup to reply.
  2. You can also use the arrow function to follow the newer ECMA script syntax ES6. Another reason is that you will not use lexical this probably so the arrow function is a better choice.

    import React from 'react';
    import { useNavigate } from 'react-router-dom'; 
    
    const MyComponent = () => {
      const navigate = useNavigate(); 
    
      const handleFormSubmit = (event) => {
        event.preventDefault(); 
        console.log("Form Submitted"); 
        navigate("/");
      }
    
      return (
        <Form onSubmit={handleFormSubmit}>
          {/* Form content */}
        </Form>
      );
    }
    
    export default MyComponent;
    
    Login or Signup to reply.
  3. The above answer is correct. You should always include e.preventDefault() though in your case, it should have navigated without this too. Make sure the routes are defined and named correctly, double check it to be sure.

    Also if the issue is not resolved, please share your App.jsx, where you are handling the navigation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search