Reputation: 437
I am trying to import useHistory from 'react-router-dom', however, I get this error: import error: 'useHistory' is not exported from 'react-router-dom'.
I have checked other answers as well such as Attempted import error: 'useHistory' is not exported from 'react-router-dom' this but to no avail. My package.json looks like this
I am using useHistory as such,
import React from 'react';
import { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
export default function Login(){
const history = useHistory();
console.log(history)
}
However, this line works fine and does not cause import issues from react-router-dom.
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'
Does anyone have an idea how to solve this issue? much appreciated.
Upvotes: 6
Views: 24284
Reputation: 425
The correct answer to your problem is that you need to confirm your use of the history hook is within the scope of a BrowserRouter - a quick fix would be to move the BrowserRouter component up a level to app.js or index.js - As long as you invoke the useHistory hook within the scope of a component that is already within the context of a BrowserRouter, you should have no issues in v5. The people who commented about v6 would still need to do this same fix, the answer is not to upgrade, although if you have the ability to upgrade, I would do so.
Suggested Fix: Render the BrowserRouter on the index.js
// index.js
...
import { BrowserRouter } from 'react-router-dom' // <=V5 not compatible with V6
render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root'));
...
Then on any component that is loaded within the component, you can use useHistory
Learn more about history and where it can load - https://github.com/remix-run/history
Upvotes: 0
Reputation: 159
UseHistory have already been replaced with useNavigate So try this👇👇
import { useNavigate } from 'react-router-dom';
Inside of your function:
const navigate = useNavigate();
navigate('/home')
I hope this worked👌
Upvotes: 14
Reputation: 1
// `useHistory` has been replaced by `useNavigate` in react-router-dom v6
import { useNavigate } from "react-router-dom";
function Invoices() {
let navigate = useNavigate();
return
(enter code here
<div>
<NewInvoiceForm
onSubmit={async event => {
let newInvoice = await createInvoice(
event.target
);
navigate(`/invoices/${newInvoice.id}`);
}}
/>
</div>
);
}
Upvotes: -1
Reputation: 1291
useNavigate
if you install v6 or more than react-router-dom": ^6.2.1
import { useNavigate } from "react-router-dom";
let navigate = useNavigate();
const onSubmit = async (e) => {
e.preventDefault();
await axios.post("http://localhost:3001/users", user);
navigate(`/`);
};
Upvotes: 1