Programmatic Redirects
Redirect users programmatically after actions like form submission.
Use useHistory to redirect users after an action.
Using useHistory
import { useHistory } from "react-router-dom";
const Create = () => {
const history = useHistory();
const handleSubmit = (e) => {
e.preventDefault();
const blog = { title, body, author };
fetch("http://localhost:8000/blogs", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(blog)
}).then(() => {
history.push("/");
});
};
};history.push("/") redirects the user to the homepage after the blog is created.