I'm quite new to react router and I'm having few difficulties. I have no problems using history inside a ponent. Howver, I have a function outside the said ponent and it can't detect history. I tried alot of things but to no avail. It gives me a history is undefined
error
UserAvatar.js
import {withRouter} from "react-router-dom";
const signOut = (history) => {
console.log(history);
localStorage.removeItem("token");
localStorage.removeItem("user");
history.replace('/sign-in');
};
export class UserAvatar extends Component {
render() {
const content = (
<div>
<p>Content</p>
<Button className="sign-out" onClick={() => signOut(this.props.history)}>Sign-out</Button>
</div>
);
export default withRouter(UserAvatar, signOut)
any ideas would be of great help Thanks!
I'm quite new to react router and I'm having few difficulties. I have no problems using history inside a ponent. Howver, I have a function outside the said ponent and it can't detect history. I tried alot of things but to no avail. It gives me a history is undefined
error
UserAvatar.js
import {withRouter} from "react-router-dom";
const signOut = (history) => {
console.log(history);
localStorage.removeItem("token");
localStorage.removeItem("user");
history.replace('/sign-in');
};
export class UserAvatar extends Component {
render() {
const content = (
<div>
<p>Content</p>
<Button className="sign-out" onClick={() => signOut(this.props.history)}>Sign-out</Button>
</div>
);
export default withRouter(UserAvatar, signOut)
any ideas would be of great help Thanks!
Share Improve this question asked Jul 5, 2018 at 13:38 Jason Jason 2818 silver badges19 bronze badges3 Answers
Reset to default 5You can use the history library to manually create the history outside of your ponent tree and give that to your Router
ponent. This way you can import the history
object wherever you need it.
Example
// history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
// index.js
import { Router, Route, Link } from 'react-router-dom';
import history from './history';
ReactDOM.render(
<Router history={history}>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/user">User</Link></li>
</ul>
<Route exact path="/" ponent={HomePage} />
<Route path="/user" ponent={UserAvatar} />
</div>
</Router>,
document.getElementById('root')
);
Issue is with signout function definition. You are making history as local variable to your function. Remove param history from signout method. this should help atleast to print it correctly.
const signOut = () => { // remove hestory from hear as its a globally available.
console.log(history);
localStorage.removeItem("token");
localStorage.removeItem("user");
history.replace('/sign-in');
};
you can use this package history
import it in your file
import { createBrowserHistory } from 'history'
;
then use it like this
createBrowserHistory().push('/')
;
then you can reload the dom
window.location.reload()
;`