Created
March 12, 2020 09:06
-
-
Save abhagsain/0d3ab4e53bf245fab8e21864314e6b95 to your computer and use it in GitHub Desktop.
Protected Route Using React Router Dom
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const PrivateRoute = ({ component: Component, ...args }) => { | |
| // user is the authenticated user pulled from the React Context | |
| const { user } = useContext(AuthContext); | |
| return ( | |
| <Route | |
| {...args} | |
| render={props => { | |
| return user ? ( | |
| <Component {...props} /> | |
| ) : ( | |
| <Redirect | |
| to={{ | |
| pathname: "/login", | |
| state: { | |
| from: props.location, | |
| }, | |
| }} | |
| /> | |
| ); | |
| }} | |
| /> | |
| ); | |
| }; | |
| function Login(props) { | |
| const { user } = useContext(AuthContext); | |
| const { from } = props.location.state || { from: { pathname: "/" } }; | |
| if (user) { | |
| return <Redirect to={from} />; | |
| } | |
| return ( | |
| <React.Fragment> | |
| <Form | |
| props={props} | |
| authMessage={props.location.state && "You need to login first"} | |
| /> | |
| </React.Fragment> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment