Skip to content

Instantly share code, notes, and snippets.

@GergKllai1
Last active October 30, 2019 20:37
Show Gist options
  • Save GergKllai1/4e9b31b5f63915aa793f9b5a171a874b to your computer and use it in GitHub Desktop.
Save GergKllai1/4e9b31b5f63915aa793f9b5a171a874b to your computer and use it in GitHub Desktop.
Restricting routes with ternary operators and Redirect
import React from "react";
import { Switch, Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import MainIndex from "./MainIndex";
import LoginPage from "./LoginPage";
import RestrictedPage from "./RestrictedPage";
import OnlyTeacher from "./OnlyTeacher";
import OnlyStudent from "./OnlyStudent";
export const Content = ({ user }) => {
return (
<>
<Switch>
<Route exact path="/index" component={MainIndex} />
{user.isSignedIn ? (
<Route exact path="/restricted" component={RestrictedPage} />
) : (
<Redirect to="/login" />
)}
{user.role === "teacher" ? (
<Route exact path="/only-teacher" component={OnlyTeacher} />
) : (
<Redirect to="/index" />
)}
{user.role === "student" ? (
<Route exact path="/only-student" component={OnlyStudent} />
) : (
<Redirect to="/index" />
)}
<Route exact path="/login" component={LoginPage} />
</Switch>
</>
);
};
const mapStateToProps = state => ({
user: state.userReducer
});
export default connect(
mapStateToProps,
null
)(Content);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment