DEV Community

artemismars
artemismars

Posted on

React - How to redirect

import {useHistory} from 'react-router-dom'
Enter fullscreen mode Exit fullscreen mode

useHistory was the thing to redirect in React.
But in react-router-dom v6, it changed.

import {useNavigate} from 'react-router-dom'
const navigate = useNavigate();

const handleSubmit = (e) => {
  e.preventDefault()
  // some codes..
  fetch('http://localhost:8000/notes', {
    method: 'POST',
    header: {'Content-Type': 'application/json'},
    body: JSON.stringify({title, details, category}),
  }).then(() => navigate('/')) // navigate() here! redirect to '/'
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)