Blog>
Snippets

Implementing Programmatic Navigation

Provide an example of using the `useNavigate` hook for navigating to a different route programmatically, such as redirecting a user after a form submission.
import { useNavigate } from 'react-router-dom';
First, import the useNavigate hook from react-router-dom.
function Form() {
  const navigate = useNavigate();

  function handleSubmit(event) {
    event.preventDefault();
    // Form submission logic here
    
    // Navigate to a different route after form submission
    navigate('/success');
  }

  return (
    <form onSubmit={handleSubmit}>
      {/* Form inputs here */}
      <button type='submit'>Submit</button>
    </form>
  );
}
Define a component that uses the useNavigate hook. When the form is submitted, the navigate function is called with the path to navigate to, in this case, '/success'.