DEV Community

khaledattia
khaledattia

Posted on

Programmatic Navigation in React using react-router-dom

I was trying to make a redirect to somewhere else after submitting a form, and by looking at the developers communities for a solution to do so, unfortunately, most of them only show the way using the Link component and have already been removed from this react version@6, and after looking at the react router official website I got the answer.

This blog mainly aims to be a refuge to those people who come here looking for the answers to this problem.

useNavigate Hook

The useNavigate hook returns a function that lets you navigate programmatically, which it returns a function has two signatures

  • Either pass a To value (same type as ) with an optional second { replace, state } arg or
  • Pass the delta you want to go in the history stack. For example, navigate(-1) is equivalent to hitting the back button.

1. to

for example after a form is submitted.


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

export const SignupForm = () => {
  let navigate = useNavigate();

  async function handleSubmit(event) {
    event.preventDefault();
    await submitForm(event.target);
    navigate("/success");
  }

  return <form onSubmit={handleSubmit}>{/* ... */}</form>;
}

Enter fullscreen mode Exit fullscreen mode

2. option - state

An object to store on location state. This is useful for state that doesn’t need to be in the URL but is associated with a route transition. Think of it like “post” data on a server.

const NewTodo = () => (
  <TodoForm
    onSubmit={async todo => {
      let id = await createNewTodo(todo)
      // put some state on the location
      navigate("/todos", { state: { newId: id } })
    }}
  />
)

const Todos = props => (
  <div>
    {todos.map(todo => (
      <div
        style={{
          background:
            // read the location state
            todo.id === props.location.state.newId
              ? "yellow"
              : ""
        }}
      >
        ...
      </div>
    ))}
  </div>
)
Enter fullscreen mode Exit fullscreen mode

3. option - replace

Normally a call to navigate will push a new entry into the history stack so the user can click the back button to get back to the page. If you pass replace: true to navigate then the current entry in the history stack will be replaced with the new one.

An example is when the user clicks a “purchase” button but needs to log in first, after they log in, you can replace the login screen with the checkout screen you wanted them to be at. Then when they click the back button they won’t see the login page again.

navigate("/some/where", { replace: true })
Enter fullscreen mode Exit fullscreen mode

also you can check react router website Link

Top comments (0)