Last active
November 9, 2017 04:18
-
-
Save ryandrewjohnson/3e2deface1e56502709e7cdbed5e832b to your computer and use it in GitHub Desktop.
Help with traversing react HOC's
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
/* | |
I will try my best to describe what I'm trying to accomplish, and what the problem is... | |
react-router has a <Switch> component that loops through it's children, and assumes each child is of type <Route>. | |
I have created a custom <RouteByUserRoleType> that is a connected component that will render a <Route> component, if the current | |
user's role matches the type prop passed from the component. If it doens't match then null would be returned. | |
// Desired behaviour | |
Ideally <Switch> would traverse each child until it finds either a <Route> component, or null. If it finds a <Route> then that would be | |
treated like a normal <Route> component in a switch. | |
// Current behaviour | |
Because <Switch> assumes each child component is already of type <Route> it will not care whether <RouteByUserRoleType> renders a <Route> | |
or null. | |
Is the desired behaviour even doable? I know you can traverse React.Children, but since <RouteByUserRoleType> is actually wrapped with | |
both `withRouter` and `connect` I'm not even sure if it's possible to get access to the underlying components that are rendered. | |
*/ | |
// both routes have the same path, but only one should be used based on type. | |
<Switch> | |
<RouteByUserRoleType path="/" type="admin" /> | |
<RouteByUserRoleType path="/" type="client" /> | |
</Switch> | |
// RouteByUserRoleType | |
const CustomRoute = props => { | |
const {type, types, userRoleType, ...rest} = props; | |
return type === userRoleType | |
? <Route {...rest} /> | |
: null; | |
}; | |
const mapStateToProps = (state: IicoState) => { | |
return { | |
userRoleType: getUserRoleType(state) | |
}; | |
}; | |
export const RouteByUserRoleType = withRouter( | |
connect(mapStateToProps)(CustomRoute) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment