Bharat Soni
Bharat Soni

Reputation: 2902

How to navigate programmatically react-router-dom v6

I came back to react world after a few years. And things certainly have changed for good. I'm using MemoryRouter for my app. And I can navigate fine by using Link. But useNaviate hook is not working as expected. It does nothing on the page. Could you please help me here? Here is my code:

Router:

<MemoryRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/dashboard" element={<Dashboard />} />
  </Routes>
</MemoryRouter>

Here is how I'm trying the navigation:

function Home() {
  // demo purpose
  const navigate = useNavigate()
  
  navigate('/dashboard')
}

I'm not sure if I'm using it right, or if I need to do something else here.

Upvotes: 1

Views: 1072

Answers (3)

Drew Reese
Drew Reese

Reputation: 202605

The code is calling navigate as an unintentional side-effect directly in the function component body.

Either call navigate from a component lifecycle or callback to issue an imperative navigation action:

function Home() {
  const navigate = useNavigate()

  useEffect(() => {
    if (/* some condition */) {
      navigate('/dashboard');
    }
  }, [/* dependencies? /*]);
  
  ...
}

Or conditionally render the Navigate component to a declarative navigation action:

function Home() {
  ...

  if (/* some condition */) {
    return <Navigate to="/dashboard" />;
  };
  
  ...
}

Upvotes: 1

Priyen Mehta
Priyen Mehta

Reputation: 1187

Make your navigate in function call or in useEffect like this:

function Home() {
// demo purpose
const navigate = useNavigate()
  useEffect(() => {
    navigate('/dashboard')
  }, []);
}

Upvotes: 0

Bharat Soni
Bharat Soni

Reputation: 2902

The problem was that I was calling navigate directly when the component was rendering. It should either be called in an event, or it should be called in useEffect hook.

Upvotes: 0

Related Questions