Posts

Showing posts with the label React Router

Cannot Read Property 'history' Of Undefined (useHistory Hook Of React Router 5)

Answer : Its because the react-router context isn't set in that component. Since its the <Router> component that sets the context you could use useHistory in a sub-component, but not in that one. Note to other people that run into this problem and already have wrapped the component with Router component. Make sure that Router and the useHistory hook are imported from the same package. The same error can be thrown when one of them are imported from react-router and the other one from react-router-dom and the package versions of those packages don't match. Don't use both of them, read about the difference here. useHistory won't work in the component where you have your Routes because the context which is needed for useHistory is not yet set. useHistory will work on any child component or components which your have declared in your Router but it won't work on Router 's parent component or Router component itself.

Automatic Redirect After Login With React-router

Answer : React Router v3 This is what I do var Router = require('react-router'); Router.browserHistory.push('/somepath'); React Router v4 Now we can use the <Redirect> component in React Router v4. Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects. import React, { Component } from 'react'; import { Redirect } from 'react-router'; export default class LoginComponent extends Component { render(){ if(this.state.isLoggedIn === true){ return (<Redirect to="/your/redirect/page" />); }else{ return (<div>Login Please</div>); } } } Documentation https://reacttraining.com/react-router/web/api/Redirect React Router v0.13 The Router instance returned from Router.create can be passed around (or, if inside a React component, you can g...