Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use history using withRouter outside component

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!

like image 655
Jason Avatar asked Jul 05 '18 13:07

Jason


People also ask

How do you access history outside the react component?

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.

How do you use .push history in react?

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.

How do I access my router history response?

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.


1 Answers

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')
);
like image 172
Tholle Avatar answered Sep 21 '22 18:09

Tholle