Created
October 30, 2019 17:28
-
-
Save GergKllai1/636e6112da2986d941cc844ad58cbf4d to your computer and use it in GitHub Desktop.
Restricting route
This file contains 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
import React, { useEffect, useState } from "react"; | |
import { connect } from "react-redux"; | |
import { Redirect, Route } from "react-router-dom"; | |
const CustomRoute = props => { | |
const [returnedRoute, setReturnedRoute] = useState(""); | |
useEffect(() => { | |
switch (props.condition) { | |
case "teacher": | |
return setReturnedRoute( | |
props.user.role === "teacher" ? ( | |
<Route {...props} /> | |
) : ( | |
<Redirect to="/index" /> | |
) | |
); | |
case "student": | |
return setReturnedRoute( | |
props.user.role === "student" ? ( | |
<Route {...props} /> | |
) : ( | |
<Redirect to="/index" /> | |
) | |
); | |
case "signedIn": | |
return setReturnedRoute( | |
props.user.isSignedIn ? <Route {...props} /> : <Redirect to="/index" /> | |
); | |
default: | |
return setReturnedRoute(<Route {...props} />); | |
} | |
}, [props.user]); | |
return <>{returnedRoute}</>; | |
}; | |
const mapStateToProps = state => ({ | |
user: state.userReducer | |
}); | |
export default connect( | |
mapStateToProps, | |
null | |
)(CustomRoute); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment