Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect React Router from Context Provider

I'm new to React Router and trying to do a redirect from inside a provider using the new Conext API. basically my provider looks like this.

/* AuthContext.js */

class AuthProvider extends React.Component {

  state = { isLoggedIn: false }

  constructor() {
    super()
    this.login = this.login.bind(this)
    this.logout = this.logout.bind(this)
  }

  login() {

    this.setState({ isLoggedIn: true })

    // Need to redirect to Dashboard Here

  }

  logout() {
    this.setState({ isLoggedIn: false })
  }

  render() {
    return (
      <AuthContext.Provider
        value={{
          isLoggedIn: this.state.isLoggedIn,
          login: this.login,
          logout: this.logout
        }}
      >
        {this.props.children}
      </AuthContext.Provider>
    )
  }
}

const AuthConsumer = AuthContext.Consumer

export { AuthProvider, AuthConsumer }

I've read a lot about how to pass the history object using props and how to use a component but I can't see how these approaches would work here. My context provider sits at the top of the tree so it's not a child of the Router so I can't pass props. It's also not a standard component so I can't just insert a component, unless I've misunderstood something (which is very possible).

Edit: Looks like the way to go is withRouter, but how to export my AuthProvider in the code above so that history.push is available in my login function? As you can see I'm exporting multiple components wrapped in {} so can you wrap one of these in a HOC and do you have to explicitly pass history in or is it always available inside the component that's being wrapped?

like image 867
jonhobbs Avatar asked Jul 23 '18 11:07

jonhobbs


1 Answers

use withRouter, sth like this to get access of history.

 const AuthButton = withRouter( ({ history }) =>history.push("/"));

Try This:

    import { Route } from "react-router-dom";

  class AuthProvider extends React.Component {
    yourFunction = () => {
      doSomeAsyncAction(() =>
        this.props.history.push('/dashboard')
      )
    }

    render() {
      return (
        <div>
          <Form onSubmit={ this.yourFunction } />
        </div>
      )
    }
  }

  export default withRouter(AuthProvider);

Best explanation can be found here: Programmatically navigate using react router

like image 135
Srinivas Avatar answered Nov 01 '22 20:11

Srinivas