skip to Main Content

I have a react application where I use react-router-dom to set up my client routes as follows in my app.js file:

<Route path="/admin" element={<AdminLayout />}>
    <Route index path="add-article" element={<AddArticleForm />} />
    <Route path="success" element={<Success />} />
</Route>

In my AddAritcleForm component, I would like to programmatically navigate to /admin/success when there is a successful response from the server. Please see below:

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

const AddArticleForm = () => {
  const navigate = useNavigate();
  const handleSubmit = async (event) => {
    event.preventDefault();
    const form = event.target;

    try {
      const request = await fetch('http://localhost:8000/add-article', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          url: form.url.value,
          title: form.title.value,
          author: form.author.value,
          section: form.section.value,
          content: form.content.value,
          tags: form.tags.value,
          excerpt: form.excerpt.value,
        }),
      });

      const response = await request.json();

      if (response) {
        console.log(response);
        navigate('/admin/success');
      }
    } catch (error) {
      console.log('error', error);
      //   Handle error
    }
  };
  return (
    <>
      <h2>Create New Article</h2>
      <form onSubmit={handleSubmit}>
        ...jsx code...
        <button type="submit">Submit</button>
      </form>
    </>
  );
};

export default AddArticleForm;

I can see in my backend console that the response is sent properly, but for some reason, the navigate() function is not navigating to /admin/success after receiving the response. What might be the reason that react-router-dom is not navigating upon receiving the response?

3

Answers


  1. I wouldn’t wrap a tags with a parent . It is simplest to just have 2 separate tags:

    <Route path="/admin/add-article" element={<AddArticleForm />} />
    <Route path="/admin/success" element={<Success />} />
    
    Login or Signup to reply.
  2. import { Outlet } from 'react-router-dom';
    
    ...
    
    const AdminLayout = () => {
      return (
        <>
          <h1>AdminLayout</h1>
           ....
    
    
          <Outlet />
        </>
      );
    };
    

    Add Outlet at the end.

    refer ->

    Login or Signup to reply.
  3. Here’s a test example that may help:
    https://playcode.io/1501535

    App.jsx

    import React from 'react';
    import { BrowserRouter as Router, Routes, Route } from "react-router-dom" ;
    import { Home } from './Home.jsx';
    import { Admin } from './Admin.jsx';
    import { Success } from './Success.jsx';
    
    export function App() {
     return (
            <Router>
                <Routes>
                    <Route path='/' element={<Home />} >
                      <Route path='Admin' element={<Admin />}>  
                       <Route path='Success' element={<Success />}/>  
                      </Route>
                    </Route>
                    
                </Routes>
            </Router>
        );
    }
    
    // Log to console
    console.log('Hello console')
    

    Home.jsx

    import { useNavigate, Outlet } from 'react-router-dom';
    
    export function Home() {
      const navigate = useNavigate();
     
        return (
            <div>
                <h1>Home</h1>
                <button onClick={() => navigate("/Admin")}>test</button>
                <Outlet />
            </div>
        );
    }
    

    Admin.jsx

    import { useNavigate, Outlet } from 'react-router-dom';
    export function Admin() {
      const navigate = useNavigate();
        return (
            <div>
                <h1>Admin</h1>
                <button onClick={() => navigate("/Admin/Success")}>test</button> 
                <Outlet />
            </div>
        );}
    

    Success.jsx

    export function Success() {
        return (
            <div>
                <h1>Success</h1>
            </div>
        );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search