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
I wouldn’t wrap a tags with a parent . It is simplest to just have 2 separate tags:
Add Outlet at the end.
refer ->
Here’s a test example that may help:
https://playcode.io/1501535
App.jsx
Home.jsx
Admin.jsx
Success.jsx