5

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!

Jason
  • 281
  • 8
  • 19

3 Answers3

5

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')
);
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • Hello! from what I understood, history should be able to redirect you to a component(?) when I tried this implementation, the url does change but the component stays the same. Could you please give me some insights on why this happens? – Jason Jul 05 '18 at 14:05
  • @Jason Yes, `history.replace` or `history.push` should render the routes that match the new url. I'm not sure what goes wrong for you. Maybe you could create a [CodeSandbox](https://codesandbox.io/) or something similar to show your issue? – Tholle Jul 05 '18 at 14:10
  • So I think it would be better not to use the hook ```useHistory``` once you opt for this approach, right? Or do you think that I could also use ```useHistory``` despite passing a "custom" history to my Router component? – Watchmaker Jul 22 '21 at 09:49
0

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');
};
Manoj
  • 1,175
  • 7
  • 11
  • Hello! Thanks for the response. I tried doing this and I get a `unexpected use of history` error. I know this might be a noobie question but how would I refer to history in this case? this.props.history or just history? just history doesnt seem to work – Jason Jul 05 '18 at 13:44
0

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();`

Jaman-Dedy
  • 567
  • 5
  • 3