I'm quite new to react router and I'm having few difficulties. I have no problems using history inside a component. Howver, I have a function outside the said component 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!
We would obviously want some additional logic in there, but the point is that we can access the history object through props , even though no props were passed to Login , and use history. push to push a new entry onto the history stack.
push() Method. history. push() is another approach where we make use of the history props React Router provides while rendering a component. In other words, this works when the component is being rendered by React Router, bypassing the component as a Component prop to a Route.
Through the history object, we can access and manipulate the current state of the browser history. All we need to do is to call the useHistory hook inside a functional component: import { useHistory } from 'react-router-dom'; const App = () => { const history = useHistory(); const redirect = () => { history.
You can use the history library to manually create the history outside of your component tree and give that to your Router
component. 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="/" component={HomePage} />
<Route path="/user" component={UserAvatar} />
</div>
</Router>,
document.getElementById('root')
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With