useHistory is not exported from react-router-dom


You might get this error after upgrading react-router-dom to version 6.x.x

Attempted import error: ‘useHistory’ is not exported from ‘react-router-dom’. This error occurred during the build time and cannot be dismissed.

Solution:

You need to replace useHisotry with useNavigate:

  1. Navigate to Path
    • Replace history.push(‘/home’) with navigate(‘/home’)
  2. Replace Page
    • Change history.replace(‘/dashboard’) with navigate(‘/dashboard’, { replace: true })

The following are similar methods of go,goForward,goBack in navigate:

  1. Go Forward to next page
    • const { goForward } = useHistory();
    • onClick of goForward() -> to navigate(1)
  2. Go to Previous page
    • const { goBack} = useHistory() to {goBack()} to navigate(-1)
  3. Go to 2 pages before
    • const { go, } = useHistory()
    • change go(2) to navigate(2)

Hope this helps