Programmatically navigating using the Navigation Hook
Whenever we want to programmatically navigate instead of having a link for the user to click, we can use the Navigation Hook provided by React Router. The Navigation Hook provides a function to navigate programmatically.
Let’s get started using the Navigation Hook now:
- Edit
src/components/post/CreatePost.jsxand import theuseNavigatefunction:import { useNavigate } from 'react-router' - Define a Navigate Hook inside the
CreatePostcomponent:export function CreatePost() { const [username] = useContext(UserContext) const navigate = useNavigate() - Inside the Action State Hook, get the result from the mutation and then redirect to the
ViewPostpage of the newly created post:const [error, submitAction, isPending] = useActionState( async (currentState, formData) => { const title = formData.get('title') const content...