Last active
October 30, 2019 20:28
-
-
Save GergKllai1/92e14f8e682ed8646bb3c4d1ee9faa78 to your computer and use it in GitHub Desktop.
Custom link component for restricting react-router-links
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 { Link } from "react-router-dom"; | |
const CustomLink = props => { | |
const [returnedLink, setReturnedLink] = useState(null); | |
useEffect(() => { | |
switch (props.condition) { | |
case "teacher": | |
return setReturnedLink( | |
props.user.role === "teacher" ? <Link {...props}>{props.children}</Link> : null | |
); | |
case "student": | |
return setReturnedLink( | |
props.user.role === "student" ? <Link {...props}>{props.children}</Link> : null | |
); | |
case "signedIn": | |
return setReturnedLink( | |
props.user.isSignedIn ? <Link {...props}>{props.children}</Link> : null | |
); | |
case "signedOut": | |
return setReturnedLink( | |
props.user.isSignedIn ? null : <Link {...props}>{props.children}</Link> | |
); | |
default: | |
return setReturnedLink(<Link {...props}>{props.children}</Link>); | |
} | |
}, [props.user]); | |
return <>{returnedLink}</>; | |
}; | |
const mapStateToProps = state => ({ | |
user: state.userReducer | |
}); | |
export default connect( | |
mapStateToProps, | |
null | |
)(CustomLink); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment